1473
votes

This came to my mind after I learned the following from this question:

where T : struct

We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.

Some of us even mastered the stuff like Generics, anonymous types, lambdas, LINQ, ...

But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?

Here are the revealed features so far:


Keywords

Attributes

Syntax

Language Features

Visual Studio Features

Framework

Methods and Properties

Tips & Tricks

  • Nice method for event handlers by Andreas H.R. Nilsson
  • Uppercase comparisons by John
  • Access anonymous types without reflection by dp
  • A quick way to lazily instantiate collection properties by Will
  • JavaScript-like anonymous inline-functions by roosteronacid

Other

0

296 Answers 296

1
4 5
6
7 8
10
9
votes

I quite enjoy implicit generic parameters on functions. For example, if you have:

public void DoStuff<T>(T value);

Instead of calling it like this:

DoStuff<int>(5);

You can:

DoStuff(5);

And it'll work out the generic type from the parameter's type.

  • This doesn't work if you're calling the method through reflection.
  • I remember having some weird problems on Mono.
1
  • But it works only with one type parameter. As soon as you add two, it will force you to explicitely specify the Types.
    – user65199
    Jul 17, 2009 at 13:05
9
votes

Working with enums.

Convert a string to an Enum:

enum MyEnum
{
    FirstValue,
    SecondValue,
    ThirdValue
}

string enumValueString = "FirstValue";
MyEnum val = (MyEnum)Enum.Parse(typeof(MyEnum), enumValueString, true)
  • I use this to load the value of CacheItemPriority in my ASP.NET applications from a settings table in a database so that I can control caching (along with other settings) dynamically without taking the application down.

When comparing variables of type enum, you don't have to cast to int:

MyEnum val = MyEnum.SecondValue;
if (val < MyEnum.ThirdValue)
{
    // Do something
}
0
9
votes

To test if an IEnumerable<T> is empty with LINQ, use:

IEnumerable<T>.Any();

  • At first, I was using (IEnumerable<T>.Count() != 0)...
    • Which unnecessarily causes all items in the IEnumerable<T> to be enumerated.
  • As an improvement to this, I went on to use (IEnumerable<T>.FirstOrDefault() == null)...
    • Which is better...
  • But IEnumerable<T>.Any() is the most succinct and performs the best.
5
  • Why is enumerable.FirstOrDefault() == null an improvement?
    – Jim G.
    Jun 2, 2010 at 20:00
  • 1
    Because it doesn't potentially cause the entire collection to be enumerated.
    – Grokys
    Jun 2, 2010 at 21:50
  • 1
    But doesn't Any() quit on the first find too?
    – Jim G.
    Jun 4, 2010 at 19:09
  • Yes, it does. That's why it's the best solution.
    – Grokys
    Jun 5, 2010 at 11:08
  • Enumerable.Count() == 0 is faster than Enumerable.Any() in cases where the collection has been enumerated and is an IList or array.
    – MattDavey
    Mar 6, 2012 at 15:07
8
votes

I'm pretty sure everyone is familiar with operator overloading, but maybe some aren't.

class myClass
{
    private string myClassValue = "";

    public myClass(string myString)
    {
        myClassValue = myString;
    }

    public override string ToString()
    {
        return myClassValue;
    }

    public static myClass operator <<(myClass mc, int shiftLen)
    {
        string newString = "";
        for (int i = shiftLen; i < mc.myClassValue.Length; i++)
            newString += mc.myClassValue[i].ToString();
        mc.myClassValue = newString.ToString();
        return mc;
    }

    public static myClass operator >>(myClass mc, int shiftLen)
    {
        char[] newString = new char[shiftLen + mc.myClassValue.Length];

        for (int i = shiftLen; i < mc.myClassValue.Length; i++)
            newString[i] += mc.myClassValue[i - shiftLen];

        mc.myClassValue = new string(newString);
        return mc;
    }

    public static myClass operator +(myClass mc, string args)
    {
        if (args.Trim().Length > 1)
            mc.myClassValue += args;
        return mc;
    }

    public static myClass operator -(myClass mc, string args)
    {
        if (args.Trim().Length > 1)
        {
            Regex rgx = new Regex(args);
            mc.myClassValue = rgx.Replace(mc.myClassValue, "");
        }
        return mc;
    }
}

I think it's pretty cool to be able to shift a string left and right using << and >> or to remove a set of strings that follow a regular expression pattern using -=

myClass tmpClass = new myClass("  HelloWorld123");
tmpClass -= @"World";
tmpClass <<= 2;
Console.WriteLine(tmpClass);
5
  • 4
    As anyone who's worked with a C++ library that has lots of overloaded operators will tell you, overloaded operators are evil, evil, evil. Just write a method to do it.
    – endian
    Oct 23, 2008 at 8:13
  • 3
    Great for math classes. Makes, for example, multiplying vector and matrices very to read, just aVector = anotherVector* aMatrix; instead of aVector=anotherVector.Multiply(aMatrix);
    – Sorskoot
    Jan 21, 2009 at 9:24
  • 2
    Great for math classes, as @Sorskoot said, but that's about it. For pretty much any other class they're just really bad method names. Sep 3, 2009 at 4:56
  • 1
    There are certain limited cases, in addition to mathematical classes, where certain operators make sense. I see nothing wrong with, say, myCollection += anItem; or if(someObject == anotherObject) {}.
    – snarf
    Oct 17, 2009 at 18:07
  • I think if you're going to overload operators like this you should a) make the class immutable and b) definitely NOT return a reference to one of the operands.
    – MattDavey
    Mar 6, 2012 at 15:01
8
votes

Instead of doing something cheesy like this:

Console.WriteLine("{0} item(s) found.", count);

I use the following inline trick:

Console.WriteLine("{0} item{1} found.", count, count==1 ? "" : "s");

This will display "item" when there's one item or "items" when there are more (or less) than 1. Not much effort for a little bit of professionalism.

5
  • 1
    THis is fine for debugging but you'll hit a complete nightmare when you want to get into I18N and L10N
    – Jeff Yates
    May 8, 2009 at 18:22
  • sweet solution to this often encountered issue Jun 4, 2009 at 13:23
  • 3
    yeah! internationalization will be a horror, but you could do the following: Console.WriteLine("{0} {1} found.", count, count==1 ? "item" : "items"); Jun 5, 2009 at 1:00
  • @Peter I'm assuming you meant: Console.WriteLine("{0} {1}", count, count==1 ? "item found." : "items found.");
    – rein
    Jun 19, 2009 at 13:18
  • 6
    I use a Pluralise(value, singularname, pluralname) method that spits out the entire "5 items" string. This is much more readable, supports "goose/geese" pluralisation and is much easier to find and deal with when it comes to localisation. Aug 7, 2009 at 6:31
8
votes

Not a C# specific thing, but I am a ternary operations junkie.

Instead of

if (boolean Condition)
{
    //Do Function
}
else
{
    //Do something else
}

you can use a succinct

booleanCondtion ? true operation : false operation;

e.g.

Instead of

int value = param;
if (doubleValue)
{
    value *= 2;
}
else
{
    value *= 3;
}

you can type

int value = param * (tripleValue ? 3 : 2);

It does help write succinct code, but nesting the damn things can be nasty, and they can be used for evil, but I love the little suckers nonetheless

3
  • For the sake of correctness, this pattern can only be used in situations like: if(condition) a = //some value else a = // other value
    – Olmo
    Nov 24, 2008 at 22:20
  • It's great for conditional flags too -- flags = (shouldRun ? RUN : 0) | (shouldHide ? HIDE : 0);
    – lc.
    Dec 13, 2008 at 16:43
  • I think making easy to maintain code is more important than making code that fits nicely on a line. Also, if someone wants to do this: else { // Do something else // and this other thing } Suddenly your single line ternary has to be converted to curly braces.
    – jcollum
    Dec 16, 2008 at 22:27
8
votes

Expression to initialize a Dictionary in C# 3.5:

new Dictionary<string, Int64>() {{"Testing", 123}, {"Test", 125}};

8
votes

You can switch on string!

switch(name)
{
  case "Dave":
    return true;
  case "Bob":
    return false;
  default:
    throw new ApplicationException();
}

Very handy! and a lot cleaner than a bunch of if-else statements

2
  • Wow! That really is surprising -- I always used a hashtable in such a case... Note that underlying CLR code here must be completely different than in a usual switch.
    – dbkk
    Nov 16, 2008 at 9:57
  • Yes, it turns it into a bunch of gotos in CLR.
    – Arda Xi
    Jun 25, 2010 at 4:37
8
votes

C# allows you to add property setter methods to concrete types that implement readonly interface properties even though the interface declaration itself has no property setter. For example:

public interface IReadOnlyFoo
{
   object SomeReadOnlyProperty { get; }
}

The concrete class looks like this:

internal class Foo : IReadOnlyFoo
{
   public object SomeReadOnlyProperty { get; internal set; }
}

What's interesting about this is that the Foo class is immutable if you cast it to the IReadOnlyFoo interface:

// Create a Foo instance
Foo foo = new Foo();

// This statement is legal
foo.SomeReadOnlyProperty = 12345;

// Make Foo read only
IReadOnlyFoo readOnlyFoo = foo;

// This statement won't compile
readOnlyFoo.SomeReadOnlyProperty = 54321;
4
  • What if they cast it back to Foo? Mar 26, 2010 at 1:21
  • Good point. I find it useful for most interfaces to have read-only properties. After all, interfaces describe behaviour and you normally (or perhaps 'should only') invoke behaviour through methods and not setting properties.
    – Steve Dunn
    Jun 22, 2010 at 19:17
  • I usually use a protected setter for this purpose. My class has a copy constructor which allows all the values to be set from the object being passed in. I then have a derived class that overrides the "readonly" properties return new ReadOnlyObject(new WriteableVersion() { Property1 = value, //Set all writeable fields... }); Sep 3, 2010 at 20:43
  • +100 if I could for having a mutable object with an immutable interface.
    – MattDavey
    Mar 6, 2012 at 15:11
8
votes

Dictionary initializers are always useful for quick hacks and unit tests where you need to hardcode some data.

var dict = new Dictionary<int, string> { { 10, "Hello" }, { 20, "World" } };
8
votes

With LINQ it's possible to create new functions based on parameters. That's very nice if you have a tiny function which is exectued very often, but the parameters need some time to calculate.

    public Func<int> RandomGenerator
    {
        get
        {
            var r = new Random();
            return () => { return r.Next(); };
        }
    }

    void SomeFunction()
    {
        var result1 = RandomGenerator();

        var x = RandomGenerator;
        var result2 = x();
    }
6
  • Actually, that's not LINQ, but lambda expressions.
    – gimpf
    Mar 24, 2010 at 19:06
  • And if you keep creating Random objects over and over, the quality of seeds will suffer. Much better (also space and time wise) to just allocate a static one to use and define it once.
    – Rubys
    Apr 20, 2010 at 1:41
  • 2
    no, thats the interesting point, a random object is just created the first time
    – user287107
    Apr 29, 2010 at 21:10
  • 1
    +1 Not a feature on itself, but an interesting and ridiculously easy pattern for lazy initialization!
    – Abel
    Jun 29, 2010 at 7:15
  • @user287107 No, that's not true, a new random will be created every time the property is accessed. Two times in your example. However if you held on to the delegate returned from the property only a single random is created even though you can call the delegate multiple times. Jun 30, 2010 at 18:42
7
votes

Object.ReferenceEquals Method

Determines whether the specified Object instances are the same instance.

Parameters:

  • objA: System.Object - The first Object to compare.
  • objB: System.Object - The second Object to compare.

Example:

 object o = null;
 object p = null;
 object q = new Object();

 Console.WriteLine(Object.ReferenceEquals(o, p));
 p = q;
 Console.WriteLine(Object.ReferenceEquals(p, q));
 Console.WriteLine(Object.ReferenceEquals(o, p));

Difference to "==" and ".Equals":

Basically, Equals() tests of object A has the same content as object B.

The method System.Object.ReferenceEquals() always compares references. Although a class can provide its own behavior for the equality operator (below), that re-defined operator isn't invoked if the operator is called via a reference to System.Object.

For strings there isn't really a difference, because both == and Equals have been overriden to compare the content of the string.

See also this answer to another question ("How do I check for nulls in an ‘==’ operator overload without infinite recursion?").

7
votes

Explicit interface member implementation, wherein an interface member is implemented, but hidden unless the instance is cast to the interface type.

7
votes

This isn't a C# specific type, but I just found the ISurrogateSelector and ISerializationSurrogate interfaces --

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.isurrogateselector.aspx

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.isurrogateselector.aspx

Using these in conjunction with the BinaryFormatter allows for non-serializable objects to be serialized via the implementation of a surrogate class. The surrogate pattern is well-understood in computer science, particularly when dealing with the problem of serialization. I think that this implementation is just tucked away as a parameter of the constructor to BinaryFormatter, and that's too bad.

Still - VERY hidden. :)

1
  • 1
    some example on how to use it?
    – chakrit
    Jan 18, 2009 at 21:08
7
votes

dynamic keyword in C# 4.0

You can use dynamic keyword, if you want your method calls to be resolved only at the runtime.

dynamic invoker=new DynamicInvoker();
dynamic result1=invoker.MyMethod1();
dynamic result2=invoker.MyMethod2();

Here I'm implementing a dynamic invoker.

public class DynamicInvoker : IDynamicObject
    {
        public MetaObject GetMetaObject
              (System.Linq.Expressions.Expression parameter)
        {
            return new DynamicReaderDispatch (parameter);
        }
    }

    public class DynamicDispatcher : MetaObject
    {
        public DynamicDispatcher (Expression parameter) 
                   : base(parameter, Restrictions.Empty){ }

        public override MetaObject Call(CallAction action, MetaObject[] args)
        {
            //You'll get MyMethod1 and MyMethod2 here (and what ever you call)
            Console.WriteLine("Logic to invoke Method '{0}'", action.Name);
            return this; //Return a meta object
        }
    }
7
votes

You can have generic methods in a non-generic class.

7
votes

Here's one I discovered recently which has been useful:

Microsoft.VisualBasic.Logging.FileLogTraceListener

MSDN Link

This is a TraceListener implementation which has a lot of features, such as automatic log file roll over, which I previously would use a custom logging framework for. The nice thing is that it is a core part of .NET and is integrated with the Trace framework, so its easy to pick up and use immediately.

This is "hidden" because its in the Microsoft.VisualBasic assembly... but you can use it from C# as well.

2
  • A lot of people use log4net or the enterprises library's log features. Do you think that Microsoft.VisualBasic.Logging.FileLogTraceListener is a better choice?
    – tuinstoel
    Apr 4, 2009 at 19:23
  • Probably not as full featured as those other ones. But to repeat myself: "The nice thing is that it is a core part of .NET and is integrated with the Trace framework, so its easy to pick up and use immediately."
    – dso
    Apr 8, 2009 at 17:48
7
votes

The usage of the default keyword in generic code to return the default value for a type.

public class GenericList<T>
{
    private class Node
    {
        //...

        public Node Next;
        public T Data;
    }

    private Node head;

    //...

    public T GetNext()
    {
        T temp = default(T);

        Node current = head;
        if (current != null)
        {
            temp = current.Data;
            current = current.Next;
        }
        return temp;
    }
}

Another example here

7
votes

The built-in (2.0) MethodInvoker delegate is useful when you want to Invoke/BeginInvoke inline code. This avoids needing to create an actual delegate and separate method.

    void FileMessageEvent(object sender, MessageEventArgs e)
    {

        if (this.InvokeRequired == true)
        {
            this.BeginInvoke((MethodInvoker)delegate { 
                     lblMessage.Text=e.Message; 
                     Application.DoEvents(); 
                 }
            ); 

        }
    }

Resolves the error: "Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type".

7
votes

Array initialization without specifying the array element type:

var pets = new[] { "Cat", "Dog", "Bird" };
2
  • 6
    also: string[] pets = {"Cat", "Dog", "Bird"};
    – P Daddy
    Jun 14, 2009 at 19:46
  • @P Daddy thanks for reminding me I can do this even shorter and more legible
    – sehe
    Mar 24, 2011 at 0:01
7
votes

Properties to display when viewing components Properties in design view:

private double _Zoom = 1;

[Category("View")]
[Description("The Current Zoom Level")]
public double Zoom
{
get { return _Zoom;}
set { _Zoom = value;}
}

Makes things a lot easier for other users of your component libraries.

1
  • I haven't made any components so far, so this is a place I wish I could bookmark responses instead of just the question
    – Maslow
    Aug 14, 2009 at 19:43
7
votes
[field: NonSerialized]
public event EventHandler Event;

This way, the event listener is not serialized.

Just [NonSerialized] does not work, because NonSerializedAttribute can only be applied to fields.

7
votes

Cool trick to emulate functional "wildcard" arguments (like '_' in Haskell) when using lambdas:

(_, b, __) => b.DoStuff();  // only interested in b here
1
  • 9
    Not really a trick, just a naming choice. I think it looks daft since you're forced to use increasing numbers of underscores.
    – xyz
    May 6, 2009 at 12:56
7
votes

Four switch oddities by Eric Lippert

0
7
votes

The ability to use LINQ to do inline work on collections that used to take iteration and conditionals can be incredibly valuable. It's worth learning how all the LINQ extension methods can help make your code much more compact and maintainable.

0
7
votes

You can create delegates from extension methods as if they were regular methods, currying the this parameter. For example,

static class FunnyExtension {
    public static string Double(this string str) { return str + str; }
    public static int Double(this int num) { return num + num; }
}


Func<string> aaMaker = "a".Double;
Func<string, string> doubler = FunnyExtension.Double;

Console.WriteLine(aaMaker());       //Prints "aa"
Console.WriteLine(doubler("b"));    //Prints "bb"

Note that this won't work on extension methods that extend a value type; see this question.

1
  • 1
    @MattDavey: One use for this (which is actually how I discovered it) is SomeEvent += OtherEvent.Raise, where Raise is a custom extension method. The difference between that and SomeEvent += OtherEvent is left as an exercise to the reader (it's substantial). I may write a blog post about this at some point.
    – SLaks
    Mar 6, 2012 at 15:36
7
votes

Advanced Debugging

Display

The already mentioned attributes DebuggerDisplay and DebuggerBrowsable control the visibility of elements and the textual value displayed. Simply overriding ToString() will cause the debugger to use the output of that method.

If you want more complex output you can use/create a Debugger Visualizer, several examples are available here.

Son Of Strike

Microsoft provide a debugger extension known as SOS. This is an extremely powerful (though often confusing) extension which is an excellent way to diagnose 'leaks', more accurately unwanted references to objects no longer required.

Symbol Server for framework source

Following these instructions will allow you to step through the source of some parts of the framework.

Changes in 2010

Several enhancements and new features exist in Visual Studio 2010:

7
votes

I don't think someone has mentioned that appending ? after a value type name will make it nullable.

You can do:

DateTime? date = null;

DateTime is a structure.

2
  • Nullable<T> is not a hidden feature... Aug 23, 2009 at 11:16
  • 1
    Neither is most of these... The point of this question is to show things that most c# devs may not know. I would definitely upvote this since it's not something i think most people know about. (the adding ? to get a nullable, not the nullable itself)
    – RCIX
    Sep 9, 2009 at 11:49
7
votes
HttpContext.Current.Server.Execute 

is great for rendering HTML to strings for AJAX callbacks. You can use this with a component instead of piecing together HTML string snippets. I was able to cut page bloat down a couple of hundred KB with virtually no mess. I used it like this:

Page pageHolder = new Page();
UserControl viewControl = (UserControl)pageHolder.LoadControl(@"MyComponent.ascx");
pageHolder.Controls.Add(viewControl);
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);
return output.ToString();
1
  • +1. Good tool for unit / integration testing.
    – RickNZ
    Dec 19, 2009 at 10:40
7
votes

I like

#if DEBUG
           //Code run in debugging mode

#else
           //Code run in release mode

#endif
3
  • I wouldn't say it's exactly a hidden feature, but in all the C# books that I've read, it isn't something that's talked about a lot. A nice reminder at the very least.
    – Pretzel
    May 14, 2010 at 18:49
  • 4
    Although this can be handy it should be used with care. I have seen a couple of cases where deployed code behaved differently from local code.
    – basvo
    May 20, 2010 at 10:32
  • 2
    Using the Conditional attribute is often a better solution than using #if. msdn.microsoft.com/en-us/library/aa664622%28VS.71%29.aspx
    – Ergwun
    Oct 19, 2011 at 5:26
1
4 5
6
7 8
10

Not the answer you're looking for? Browse other questions tagged or ask your own question.