[c#] Hidden Features of C#?

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

This question is related to c# hidden-features

The answer is


My favorite attribute: InternalsVisibleTo

At assembly level you can declare that another assembly can see your internals. For testing purposes this is absolutely wonderful.

Stick this in your AssemblyInfo.cs or equivalent and your test assembly get full access to all the internal stuff that requires testing.

[assembly: InternalsVisibleTo("MyLibrary.Test, PublicKey=0024...5c042cb")]

As you can see, the test assembly must have a strong name to gain the trust of the assembly under test.

Available in .Net Framework 2.0+, Compact Framework 2.0+ and XNA Framework 1.0+.


I see a lot of people replicate the functionality of Nullable<T>.GetValueOrDefault(T).


You can store colors in Enum.

public enum MyEnumColors : uint
{
    Normal          = 0xFF9F9F9F,
    Active          = 0xFF8EA98A,
    Error           = 0xFFFF0000
}

On-demand field initialization in one line:

public StringBuilder Builder
{
    get { return _builder ?? (_builder = new StringBuilder()); }
}

I'm not sure how I feel about C# supporting assignment expressions, but hey, it's there :-)


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


  • Attaching ? to a Type to make it nullable, ex: int?
  • "c:\dir" instead of @"C:\dir"

Here is a TIP of how you can use #Region directive to document your code.


Relection is so powerfull when used carefully. I used it in an e-mail templating system. The template manager would be passed an object and the html templates would have embedded fields that referred to Properties that could be retrieved off the passed object using reflection. Worked out very nicely.


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?").


When a class implements INotifyPropertyChanged and you want to inform the binding system (WPF, Silverlight, etc.) that multiple bound properties of an object (ViewModel) have changed you can raise the PropertyChanged-Event with null or String.Empty.

This is documented in MSDN, but code examples and articles often don´t explain this possibility. I found it very useful.

public class BoundObject : INotifyPropertyChanged {

    private int _value;
    private string _text;

    public event PropertyChangedEventHandler PropertyChanged;

    public int Value {
        get {
            return _value;
        }
        set {
            if (_value != value) {
                _value = value;
                OnPropertyChanged("Value");
            }
        }
    }

    public string Text {
        get {
            return _text;
        }
        set {
            if (_text != value) {
                _text = value;
                OnPropertyChanged("Text");
            }
        }
    }

    public void Init(){
        _text = "InitialValue";
        _value = 1;
        OnPropertyChanged(string.Empty);
    }

    public void Reset() {
        _text = "DefaultValue";
        _value = 0;
        OnPropertyChanged(string.Empty);
    }

    private void OnPropertyChanged(string propertyName) {
        PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);

        if (PropertyChanged != null) {
            PropertyChanged(this, e);
        }
    }
}

(I just used this one) Set a field null and return it without an intermediate variable:

try
{
    return _field;
}
finally
{
    _field = null;
}

Method groups aren't well known.

Given:

Func<Func<int,int>,int,int> myFunc1 = (i, j) => i(j);
Func<int, int> myFunc2 = i => i + 2;

You can do this:

var x = myFunc1(myFunc2, 1);

instead of this:

var x = myFunc1(z => myFunc2(z), 1);

Easier-on-the-eyes / condensed ORM-mapping using LINQ

Consider this table:

[MessageId] INT,
[MessageText] NVARCHAR(MAX)
[MessageDate] DATETIME

... And this structure:

struct Message
{
    Int32 Id;
    String Text;
    DateTime Date;
}



Instead of doing something along the lines of:

List<Message> messages = new List<Message>();

foreach (row in DataTable.Rows)
{
    var message = new Message
    {
        Id = Convert.ToInt32(row["MessageId"]),
        Text = Convert.ToString(row["MessageText"]),
        Date = Convert.ToDateTime(row["MessageDate"])
    };

    messages.Add(message);
}

You can use LINQ and do the same thing with fewer lines of code, and in my opinion; more style. Like so:

var messages = DataTable.AsEnumerable().Select(r => new Message
{
    Id = Convert.ToInt32(r["MessageId"]),
    Text = Convert.ToString(r["MessageText"]),
    Date = Convert.ToDateTime(r["MessageDate"])
}).ToList();

This approach can be nested, just like loops can.


If you're trying to use curly brackets inside a String.Format expression...

int foo = 3;
string bar = "blind mice";
String.Format("{{I am in brackets!}} {0} {1}", foo, bar);
//Outputs "{I am in brackets!} 3 blind mice"

I'd say using certain system classes for extension methods is very handy, for example System.Enum, you can do something like below...

[Flags]
public enum ErrorTypes : int {
    None = 0,
    MissingPassword = 1,
    MissingUsername = 2,
    PasswordIncorrect = 4
}

public static class EnumExtensions {

    public static T Append<T> (this System.Enum type, T value) where T : struct
    {
        return (T)(ValueType)(((int)(ValueType) type | (int)(ValueType) value));
    }

    public static T Remove<T> (this System.Enum type, T value) where T : struct
    {
        return (T)(ValueType)(((int)(ValueType)type & ~(int)(ValueType)value));
    }

    public static bool Has<T> (this System.Enum type, T value) where T : struct
    {
        return (((int)(ValueType)type & (int)(ValueType)value) == (int)(ValueType)value);
    }

}

...

//used like the following...

ErrorTypes error = ErrorTypes.None;
error = error.Append(ErrorTypes.MissingUsername);
error = error.Append(ErrorTypes.MissingPassword);
error = error.Remove(ErrorTypes.MissingUsername);

//then you can check using other methods
if (error.Has(ErrorTypes.MissingUsername)) {
    ...
}

This is just an example of course - the methods could use a little more work...


Nullable.GetValueOrDefault ?


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


Using @ for variable names that are keywords.

var @object = new object();
var @string = "";
var @if = IpsoFacto(); 

I love using the @ character for SQL queries. It keeps the sql nice and formatted and without having to surround each line with a string delimiter.

string sql = @"SELECT firstname, lastname, email
               FROM users
               WHERE username = @username AND password = @password";

Environment.NewLine

for system independent newlines.


Labeling my endregions...

#region stuff1
 #region stuff1a
 //...
 #endregion stuff1a
#endregion stuff1

Closures

Since anonymous delegates were added to 2.0, we have been able to develop closures. They are rarely used by programmers but provide great benefits such as immediate code reuse. Consider this piece of code:

bool changed = false;

if (model.Prop1 != prop1)
{
    changed = true;
    model.Prop1 = prop1;
}
if (model.Prop2 != prop2)
{
    changed = true;
    model.Prop2 = prop2;
}
// ... etc. 

Note that the if-statements above perform similar pieces of code with the exception of one line of code, i.e. setting different properties. This can be shortened with the following, where the varying line of code is entered as a parameter to an Action object, appropriately named setAndTagChanged:

bool changed = false;
Action<Action> setAndTagChanged = (action) => 
{ 
    changed = true; 
    action(); 
};

if (model.Prop1 != prop1) setAndTagChanged(() => model.Prop1 = prop1);
if (model.Prop2 != prop2) setAndTagChanged(() => model.Prop2 = prop2);

In the second case, the closure allows you to scope the change variable in your lambda, which is a concise way to approach this problem.

An alternate way is to use another unused feature, the "or equal" binary assignment operator. The following code shows how:

private bool conditionalSet(bool condition, Action action)
{
    if (condition) action();
    return condition;
}

// ...

bool changed = false;
changed |= conditionalSet(model.Prop1 == prop1, () => model.Prop1 = prop1);
changed |= conditionalSet(model.Prop2 == prop2, () => model.Prop2 = prop2);

C# 3.0's LINQ query comprehensions are full-blown monadic comprehensions a la Haskell (in fact they were designed by one of Haskell's designers). They will work for any generic type that follows the "LINQ pattern" and allows you to write in a pure monadic functional style, which means that all of your variables are immutable (as if the only variables you used were IDisposables and IEnumerables in using and foreach statements). This is helpful for keeping variable declarations close to where they're used and making sure that all side-effects are explicitly declared, if there are any at all.

 interface IFoo<T>
  { T Bar {get;}
  }

 class MyFoo<T> : IFoo<T> 
  { public MyFoo(T t) {Bar = t;}
    public T Bar {get; private set;} 
  }

 static class Foo 
  { public static IFoo<T> ToFoo<T>(this T t) {return new MyFoo<T>(t);}

    public static void Do<T>(this T t, Action<T> a) { a(t);}

    public static IFoo<U> Select<T,U>(this IFoo<T> foo, Func<T,U> f) 
     { return f(foo.Bar).ToFoo();
     }
  }

 /* ... */

 using (var file = File.OpenRead("objc.h"))
 { var x = from f in file.ToFoo()
           let s = new Scanner(f)
           let p = new Parser {scanner = s}
           select p.Parse();

   x.Do(p => 
    { /* drop into imperative code to handle file 
         in Foo monad if necessary */      
    });

 }

I think a lot of people know about pointers in C but are not sure if it works in C#. You can use pointers in C# in an unsafe context:

static void Main()
{
    int i;
    unsafe
    {               
        // pointer pi has the address of variable i
        int* pi = &i; 
        // pointer ppi has the address of variable pi
        int** ppi = &pi;
        // ppi(addess of pi) -> pi(addess of i) -> i(0)
        i = 0;
        // dereference the pi, i.e. *pi is i
        Console.WriteLine("i = {0}", *pi); // output: i = 0
        // since *pi is i, equivalent to i++
        (*pi)++;
        Console.WriteLine("i = {0}", *pi); // output: i = 1
        // since *ppi is pi, one more dereference  *pi is i 
        // equivalent to i += 2
        **ppi += 2;
        Console.WriteLine("i = {0}", *pi);// output: i = 3
    }
    Console.ReadLine();
}

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


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();

Two of my personal favourites, which I see rarely used:

  1. Snippets (particularly for properties, which was made even better for Visual Studio 2008)
  2. The ObsoleteAttribute

This isn't C# per se, but I haven't seen anyone who really uses System.IO.Path.Combine() to the extent that they should. In fact, the whole Path class is really useful, but no one uses it!

I'm willing to bet that every production app has the following code, even though it shouldn't:

string path = dir + "\\" + fileName;

InternalsVisibleTo attribute is one that is not that well known, but can come in increadibly handy in certain circumstances. It basically allows another assembly to be able to access "internal" elements of the defining assembly.


Near all the cool ones have been mentioned. Not sure if this one's well known or not

C# property/field constructor initialization:

var foo = new Rectangle() 
{ 
    Fill = new SolidColorBrush(c), 
    Width = 20, 
    Height = 20 
};

This creates the rectangle, and sets the listed properties.

I've noticed something funny - you can have a comma at the end of the properties list, without it being a syntax error. So this is also valid:

var foo = new Rectangle() 
{ 
    Fill = new SolidColorBrush(c), 
    Width = 20, 
    Height = 20,
};

Math.Max and Min to check boundaries: I 've seen this in a lot of code:

if (x < lowerBoundary) 
{
   x = lowerBoundary;
}

I find this smaller, cleaner and more readable:

x = Math.Max(x, lowerBoundary);

Or you can also use a ternary operator:

x = ( x < lowerBoundary) ? lowerBoundary : x;

@Robbie Rocketpants

"but my instincts tell me that this would cut a maximum of two type casts operations down to a maximum of one."

If you do the cast as you were suggesting in example 1 (using is & as), it results in 2 calls to the "is" operator. Because when you do "c = obj as MyClass", first it calls "is" behind the scenes, then if it fails that it simply returns null.

If you do the cast as you were suggesting in example 2,

c = (MyClass)obj

Then this actually performs the "is" operation again, then if it fails that check,it throws an exception (InvalidCastException).

So, if you wanted to do a lightweight dynamic cast, it's best to do the 3rd example you provided:

MyClass c;
if (obj is MyClass)
{
    c = obj as MyClass
}

if (c != null)
{
}

vs

MyClass c = obj as MyClass;

if (c != null)
{
}

You can see which is quicker, more consise and clearer.


OK, it may seem obvious, but I want to mention the Object.Equals method (the static one, with two arguments).

I'm pretty sure many people don't even know about it, or forget it's there, yet it can really help in some cases. For instance, when you want to compare two objects for equality, not knowing if they're null. How many times did you write something like that :

if ((x == y) || ((x != null && y != null) && x.Equals(y)))
{
    ...
}

When you can just write :

if (Object.Equals(x, y))
{
    ...
}

(Object.Equals is actually implemented exactly like in the first code sample)


Separate static fields depending on the generic type of the surrounding class.

    public class StaticConstrucEx2Outer<T> {

 // Will hold a different value depending on the specicified generic type
 public T SomeProperty { get; set; }

 static StaticConstrucEx2Outer() {
  Console.WriteLine("StaticConstrucEx2Outer " + typeof(T).Name);
 }

 public class StaticConstrucEx2Inner<U, V> {

  static StaticConstrucEx2Inner() {

   Console.WriteLine("Outer <{0}> : Inner <{1}><{2}>",
    typeof(T).Name,
    typeof(U).Name,
    typeof(V).Name);
  }

  public static void FooBar() {}
 }

 public class SCInner {

  static SCInner() {
   Console.WriteLine("SCInner init <{0}>", typeof(T).Name);
  }

  public static void FooBar() {}
 }
}


StaticConstrucEx2Outer<int>.StaticConstrucEx2Inner<string, DateTime>.FooBar();
StaticConstrucEx2Outer<int>.SCInner.FooBar();

StaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, DateTime>.FooBar();
StaticConstrucEx2Outer<string>.SCInner.FooBar();

StaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, Int16>.FooBar();
StaticConstrucEx2Outer<string>.SCInner.FooBar();

StaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, UInt32>.FooBar();

StaticConstrucEx2Outer<long>.StaticConstrucEx2Inner<string, UInt32>.FooBar();

Will produce the following output

Outer <Int32> : Inner <String><DateTime>
SCInner init <Int32>

Outer <String> : Inner <String><DateTime>
SCInner init <String>

Outer <String> : Inner <String><Int16>

Outer <String> : Inner <String><UInt32>

Outer <Int64> : Inner <String><UInt32>

new modifier

Usage of the "new" modifier in C# is not exactly hidden but it's not often seen. The new modifier comes in handy when you need to "hide" base class members and not always override them. This means when you cast the derived class as the base class then the "hidden" method becomes visible and is called instead of the same method in the derived class.

It is easier to see in code:

public class BaseFoo
{
    virtual public void DoSomething()
    {
        Console.WriteLine("Foo");
    }
}

public class DerivedFoo : BaseFoo
{
    public new void DoSomething()
    {
        Console.WriteLine("Bar");
    }
}

public class DerivedBar : BaseFoo
{
    public override void DoSomething()
    {
        Console.WriteLine("FooBar");
    }
}

class Program
{
    static void Main(string[] args)
    {
        BaseFoo derivedBarAsBaseFoo = new DerivedBar();
        BaseFoo derivedFooAsBaseFoo = new DerivedFoo();

        DerivedFoo derivedFoo = new DerivedFoo();

        derivedFooAsBaseFoo.DoSomething(); //Prints "Foo" when you might expect "Bar"
        derivedBarAsBaseFoo.DoSomething(); //Prints "FooBar"

        derivedFoo.DoSomething(); //Prints "Bar"
    }
}

[Ed: Do I get extra points for puns? Sorry, couldn't be helped.]


Marketing events as non-serializable:

[field:NonSerializable]
public event SomeDelegate SomeEvent;

My favourite is the

global::

keyword to escape namespace hell with some of our 3rd party code providers...

Example:

global::System.Collections.Generic.List<global::System.String> myList =
    new global::System.Collections.Generic.List<global::System.String>();

Some ?? weirdness :)

Delegate target =
  (target0 = target as CallTargetWithContext0) ??
  (target1 = target as CallTargetWithContext1) ??
  (target2 = target as CallTargetWithContext2) ??
  (target3 = target as CallTargetWithContext3) ??
  (target4 = target as CallTargetWithContext4) ??
  (target5 = target as CallTargetWithContext5) ??
  ((Delegate)(targetN = target as CallTargetWithContextN));

Interesting to note the last cast that is needed for some reason. Bug or by design?


Thought about @dp AnonCast and decided to try it out a bit. Here's what I come up with that might be useful to some:

// using the concepts of dp's AnonCast
static Func<T> TypeCurry<T>(Func<object> f, T type)
{
    return () => (T)f();
}

And here's how it might be used:

static void Main(string[] args)
{

    var getRandomObjectX = TypeCurry(GetRandomObject,
        new { Name = default(string), Badges = default(int) });

    do {

        var obj = getRandomObjectX();

        Console.WriteLine("Name : {0} Badges : {1}",
            obj.Name,
            obj.Badges);

    } while (Console.ReadKey().Key != ConsoleKey.Escape);

}

static Random r = new Random();
static object GetRandomObject()
{
    return new {
        Name = Guid.NewGuid().ToString().Substring(0, 4),
        Badges = r.Next(0, 100)
    };
}

The following one is not hidden, but it's quite implicit. I don't know whether samples like the following one have been published here, and I can't see are there any benefits (probably there are none), but I'll try to show a "weird" code. The following sample simulates for statement via functors in C# (delegates / anonymous delegates [lambdas]) and closures. Other flow statements like if, if/else, while and do/whle are simulated as well, but I'm not sure for switch (perhaps, I'm too lazy :)). I've compacted the sample source code a little to make it more clear.

private static readonly Action EmptyAction = () => { };
private static readonly Func<bool> EmptyCondition = () => { return true; };

private sealed class BreakStatementException : Exception { }
private sealed class ContinueStatementException : Exception { }
private static void Break() { throw new BreakStatementException(); }
private static void Continue() { throw new ContinueStatementException(); }

private static void For(Action init, Func<bool> condition, Action postBlock, Action statement) {
    init = init ?? EmptyAction;
    condition = condition ?? EmptyCondition;
    postBlock = postBlock ?? EmptyAction;
    statement = statement ?? EmptyAction;
    for ( init(); condition(); postBlock() ) {
        try {
            statement();
        } catch ( BreakStatementException ) {
            break;
        } catch ( ContinueStatementException ) {
            continue;
        }
    }
}

private static void Main() {
    int i = 0; // avoiding error "Use of unassigned local variable 'i'" if not using `for` init block
    For(() => i = 0, () => i < 10, () => i++,
        () => {
            if ( i == 5 )
                Continue();
            Console.WriteLine(i);
        }
    );
}

If I'm not wrong, this approach is pretty relative to the functional programming practice. Am I right?


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
        }
    }

On the basis that this thread should be entitled "things you didn't know about C# until recently despite thinking you already knew everything", my personal feature is asynchronous delegates.

Until I read Jeff Richter's C#/CLR book (excellent book, everyone doing .NET should read it) I didn't know that you could call any delegate using BeginInvoke / EndInvoke. I tend to do a lot of ThreadPool.QueueUserWorkItem calls (which I guess is much like what the delegate BeginInvoke is doing internally), but the addition of a standardised join/rendezvous pattern may be really useful sometimes.


Empty blocks with braces are allowed.

You can write code like this

{
    service.DoTonsOfWork(args);
}

It's helpful when you want to try something without a using or try... finally that you've already written.

//using(var scope = new TransactionScope)
{
    service.DoTonsOfWork(args);
}

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.

You can use any Unicode character in C# names, for example:

public class MyClass
{
    public string Hårføner()
    {
        return "Yes, it works!";
    }
}

You can even use Unicode escapes. This one is equivalent to the above:

public class MyClass
{
    public string H\u00e5rføner()
    {
        return "Yes, it (still) works!";
    }
}

Many people don't realize that they can compare strings using: OrdinalIgnoreCase instead of having to do someString.ToUpper(). This removes the additional string allocation overhead.

if( myString.ToUpper() == theirString.ToUpper() ){ ... }

becomes

if( myString.Equals( theirString, StringComparison.OrdinalIgnoreCase ) ){ ... }

Framework Feature

I don't know but I was quite suprised about VisualStyleRenderer and the whole System.Windows.Forms.VisualStyles-Namespace. Pretty cool!


I apologize if this one has been mentioned, but I use this a lot.

An add-in for Visual Studio was developed by Alex Papadimoulis. It's used for pasting regular text as string, string builder, comment or region.

http://weblogs.asp.net/alex_papadimoulis/archive/2004/05/25/Smart-Paster-1.1-Add-In---StringBuilder-and-Better-C_2300_-Handling.aspx

In this plugin (I also don't know if this has been mentioned) I noticed that strings are pasted with the string literal prefix:

@

I knew about these, but I didn't know about using a double quote within a literal to escape the quote.

For example

string s = "A line of text" + Environment.NewLine + "Another with a \"quote\"!!";

can be expressed as

string s = @"A line of text 
Another with a ""quote""!!";

Regarding foreach: It does not use 'duck typing', as duck typing IMO refers to a runtime check. It uses structural type checking (as opposed to nominal) at compile time to check for the required method in the type.


You can change rounding scheme using:

var value = -0.5;
var value2 = 0.5;
var value3 = 1.4;

Console.WriteLine( Math.Round(value, MidpointRounding.AwayFromZero) ); //out: -1
Console.WriteLine(Math.Round(value2, MidpointRounding.AwayFromZero)); //out: 1
Console.WriteLine(Math.Round(value3, MidpointRounding.ToEven)); //out: 1

Falling through switch-cases can be achieved by having no code in a case (see case 0), or using the special goto case (see case 1) or goto default (see case 2) forms:

switch (/*...*/) {
    case 0: // shares the exact same code as case 1
    case 1:
        // do something
        goto case 2;
    case 2:
        // do something else
        goto default;
    default:
        // do something entirely different
        break;
}

string.Empty

I know it's not fantastical (ludicrously odd), but I use it all the time instead of "".

And it's pretty well hidden until someone tells you it's there.


Full access to the call stack:

public static void Main()
{
  StackTrace stackTrace = new StackTrace();           // get call stack
  StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

  // write call stack method names
  foreach (StackFrame stackFrame in stackFrames)
  {
    Console.WriteLine(stackFrame.GetMethod().Name);   // write method name
  }
}

So, if you'll take the first one - you know what function you are in. If you're creating a helper tracing function - take one before the last one - you'll know your caller.


One thing not many people know about are some of the C#-introduced preprocessor directives. You can use #error This is an error. to generate a compiler error and #warning This is a warning.

I usually use these when I'm developing with a top-down approach as a "todo" list. I'll #error Implement this function, or #warning Eventually implement this corner case as a reminder.


  1. ?? - coalescing operator
  2. using (statement / directive) - great keyword that can be used for more than just calling Dispose
  3. readonly - should be used more
  4. netmodules - too bad there's no support in Visual Studio

Conditional string.Format:

Applies different formatting to a number depending on whether the number is positive, negative, or zero.

string s = string.Format("{0:positive;negative;zero}", i);

e.g.

string format = "000;-#;(0)";

string pos = 1.ToString(format);     // 001
string neg = (-1).ToString(format);  // -1
string zer = 0.ToString(format);     // (0)

System.Diagnostics.Debug.Assert (false);

will trigger a popup and allow you to attach a debugger to a running .NET process during execution. Very useful for those times when for some reason you can't directly debug an ASP.NET application.


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. :)


I like to use the using directive to rename some classes for easy reading like this:

// defines a descriptive name for a complexed data type
using MyDomainClassList = System.Collections.Generic.List<
  MyProjectNameSpace.MyDomainClass>;

....


MyDomainClassList myList = new MyDomainClassList();
/* instead of 
List<MyDomainClass> myList = new List<MyDomainClass>();
*/

This is also very handy for code maintenance. If you need to change the class name, there is only one place you need to change. Another example:

using FloatValue  = float; // you only need to change it once to decimal, double...

....
FloatValue val1;
...

Mixins are a nice feature. Basically, mixins let you have concrete code for an interface instead of a class. Then, just implement the interface in a bunch of classes, and you automatically get mixin functionality. For example, to mix in deep copying into several classes, define an interface

internal interface IPrototype<T> { }

Add functionality for this interface

internal static class Prototype
{
  public static T DeepCopy<T>(this IPrototype<T> target)
  {
    T copy;
    using (var stream = new MemoryStream())
    {
      var formatter = new BinaryFormatter();
      formatter.Serialize(stream, (T)target);
      stream.Seek(0, SeekOrigin.Begin);
      copy = (T) formatter.Deserialize(stream);
      stream.Close();
    }
    return copy;
  }
}

Then implement interface in any type to get a mixin.


true and false operators are really weird.

More comprehensive example can be found here.

Edit: There is related SO question What’s the false operator in C# good for?


This will not compile:

namespace ns
{
    class Class1
    {
        Nullable<int> a;
    }
}

The type or namespace name 'Nullable' could not be found (are you missing a using directive or an assembly reference?) <-- missing 'using System;'

But

namespace ns
{
    class Class1
    {
        int? a;
    }
}

will compile! (.NET 2.0).


To call the base class constructor just put base() inline with the constructor.
To call the base class method you can just put base.MethodName() inside the derived class method

class ClassA 
{
  public ClassA(int a)
  {
    //Do something
  }

  public void Method1()
  {
     //Do Something
  }
}

class ClassB : ClassA
{
  public ClassB(int a) : base(a) // calling the base class constructor
  {
    //Do something
  }

  public void Method2()
  {
    base.Method1();               // calling the base class method
  }
}

Of course you can call the methods of the base class by just saying base.MethodName()


ContextBoundObject

Not so much a C# thing as a .NET thing. It's another way of achieving DI although it can be hardwork. And you have to inherit from it which can be off putting.

http://msdn.microsoft.com/en-us/library/system.contextboundobject.aspx

I've used it to add logging when I decorate a class/method with a custom logging attribute.


Foreach uses Duck Typing

Paraphrasing, or shamelessly stealing from Krzysztof Cwalinas blog on this. More interesting trivia than anything.

For your object to support foreach, you don't have to implement IEnumerable. I.e. this is not a constraint and it isn't checked by the compiler. What's checked is that

  • Your object provide a public method GetEnumerator that
    • takes no parameters
    • return a type that has two members
      1. a parameterless method MoveNext that returns a boolean
      2. a property Current with a getter that returns an Object

For example,

class Foo
{
    public Bar GetEnumerator() { return new Bar(); }

    public struct Bar
    {
        public bool MoveNext()
        {
            return false;
        }

        public object Current
        {
            get { return null; }
        }
    }
}

// the following complies just fine:
Foo f = new Foo();
foreach (object o in f)
{
    Console.WriteLine("Krzysztof Cwalina's da man!");
}

[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.


The delegate syntax have evolved over successive versions of C#, but I still find them difficult to remember. Fortunately the Action<> and Func<> delegates are easy to remember.

For example:

  • Action<int> is a delegate method that takes a single int argument and returns void.
  • Func<int> is a delegate method that takes no arguments and returns an int.
  • Func<int, bool> is a delegate method that takes a single int argument and returns a bool.

These features were introduced in version 3.5 of the .NET framework.


Just learned, anonymous types can infer property names from the variable name:

string hello = "world";
var o = new { hello };
Console.WriteLine(o.hello);

Some concurrency utilities in the BCL might qualify as hidden features.

Things like System.Threading.Monitor are used internally by the lock keyword; clearly in C# the lock keyword is preferrable, but sometimes it pays to know how things are done at a lower level; I had to lock in C++/CLI, so I encased a block of code with calls to Monitor.Enter() and Monitor.Exit().


In addition to duncansmart's reply, also extension methods can be used on Framework 2.0. Just add an ExtensionAttribute class under System.Runtime.CompilerServices namespace and you can use extension methods (only with C# 3.0 of course).

namespace System.Runtime.CompilerServices
{
    public class ExtensionAttribute : Attribute
    { 
    }
}

The Yield keyword is often overlooked when it has a lot of power. I blogged about it awhile ago and discussed benefits (differed processing) and happens under the hood of yield to help give a stronger understanding.

Using Yield in C#


I tend to find that most C# developers don't know about 'nullable' types. Basically, primitives that can have a null value.

double? num1 = null; 
double num2 = num1 ?? -100;

Set a nullable double, num1, to null, then set a regular double, num2, to num1 or -100 if num1 was null.

http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx

one more thing about Nullable type:

DateTime? tmp = new DateTime();
tmp = null;
return tmp.ToString();

it is return String.Empty. Check this link for more details


I didn't know the "as" keyword for quite a while.

MyClass myObject = (MyClass) obj;

vs

MyClass myObject = obj as MyClass;

The second will return null if obj isn't a MyClass, rather than throw a class cast exception.


Not really hidden, but useful. When you've got an enum with flags, you can use shift-left to make things clearer. e.g.

[Flags]
public enum ErrorTypes {
    None              = 0,
    MissingPassword   = 1 << 0,
    MissingUsername   = 1 << 1,
    PasswordIncorrect = 1 << 2 
}

The Action and Func delegate helpers in conjunction with lambda methods. I use these for simple patterns that need a delegate to improve readability. For example, a simple caching pattern would be to check if the requested object exists in the cache. If it does exist: return the cached object. If it doesn't exist, generate a new instance, cache the new instance and return the new instance. Rather that write this code 1000 times for each object I may store/retrieve from the cache I can write a simple pattern method like so...

private static T CachePattern<T>(string key, Func<T> create) where T : class
{
    if (cache[key] == null)
    {
        cache.Add(key, create());
    }

    return cache[key] as T;
}

... then I can greatly simplify my cache get/set code by using the following in my custom cache manager

public static IUser CurrentUser
{
    get
    {
        return CachePattern<IUser>("CurrentUserKey", () => repository.NewUpUser());
    }
}

Now simple "everyday" code patterns can be written once and reused much more easily IMHO. I don't have to go write a delegate type and figure out how I want to implement a callback, etc. If I can write it in 10 seconds I'm much less apt. to resort to cutting/pasting simple code patterns whether they be lazy initialization and some other examples shown above...


Convert enum values to a string value

Given the enum

enum Country
{
    UnitedKingdom, 
    UnitedStates,
    UnitedArabEmirates,
}

using it:

public static void PrintEnumAsString( Country country )
{
    Console.Writeline( country.ToString() );
}

will print the name of the enum value as a string, e.g. "UnitedKingdom"


Use "throw;" instead of "throw ex;" to preserve stack trace

If re-throwing an exception without adding additional information, use "throw" instead of "throw ex". An empty "throw" statement in a catch block will emit specific IL that re-throws the exception while preserving the original stack trace. "throw ex" loses the stack trace to the original source of the exception.


I don't know if this is a hidden feature (""). Any string function.


I must admit that i'm not sure wether this performs better or worse than the normal ASP.NET repeater onItemDatabound cast code, but anyway here's my 5 cent.

MyObject obj = e.Item.DataItem as MyObject;
if(obj != null)
{
  //Do work
}

Avoid checking for null event handlers

Adding an empty delegate to events at declaration, suppressing the need to always check the event for null before calling it is awesome. Example:

public delegate void MyClickHandler(object sender, string myValue);
public event MyClickHandler Click = delegate {}; // add empty delegate!

Let you do this

public void DoSomething()
{
    Click(this, "foo");
}

Instead of this

public void DoSomething()
{
    // Unnecessary!
    MyClickHandler click = Click;
    if (click != null) // Unnecessary! 
    {
        click(this, "foo");
    }
}

Please also see this related discussion and this blog post by Eric Lippert on this topic (and possible downsides).


One that I just learned recently is that you can still call methods on a nullable value....

It turns out what when you have a nullable value:

decimal? MyValue = null;

where you might think you would have to write:

MyValue == null ? null : MyValue .ToString()

you can instead write:

MyValue.ToString()

I've been aware that I could call MyValue.HasValue and MyValue.Value...but it didn't fully click that I could call ToString().


A few from me - make of them what you will.

The attribute:

[assembly::InternalsVisibleTo("SomeAssembly")]

Allows you to expose out the internal methods/properties or data from your assembly to another assembly called 'SomeAssembly'. All protected/private stuff remains hidden.


Static constructors ( otherwise called 'Type Constructor' )

public MyClass
{
  public static MyClass()
  {
     // type init goes here
  }
  ......
}  

The keyword internal. So useful in so many ways.


A lot of this is explained already, in the standard. It's a good read for any beginner as well as expert, it's a lot to read, but it's the official standard, and it's filled with juicy details.

Once you fully understand C#, it's time to take this further to understand the fundamentals of the Common Language Infrastructure. The architecture and underpinnings of C#.

I've met a variety of programmers that don't know the difference between an object and a ValueType except the adherent limitations thereof.

Familiarize yourself with these two documents and you'll never become that person.


Another note on event handlers: you can simply create a raise extension method like so:

public static class EventExtensions {
    public static void Raise<T>(this EventHandler<T> @event, 
                                object sender, T args) where T : EventArgs {
        if(@event!= null) {
            @event(sender, args);
        }
    }
}

Then you can use it to raise events:

public class MyImportantThing {
    public event EventHandler<MyImportantEventEventArgs> SomethingHappens;
    ...
    public void Bleh() {
        SomethingHappens.Raise(this, new MyImportantEventEventArgs { X=true });
    }
}

This method has the added advantage of enforcing a coding standard (using EventHandler<>).

There isn't a point in writing the same exact function over and over and over again. Perhaps the next version of C# will finally have an InlineAttribute that can be placed on the extension method and will cause the compiler to inline the method definition (which would make this way nearly standard, and the fastest).

edit: removed temp variable inside extension method based on comments


Here are some interesting hidden C# features, in the form of undocumented C# keywords:

__makeref

__reftype

__refvalue

__arglist

These are undocumented C# keywords (even Visual Studio recognizes them!) that were added to for a more efficient boxing/unboxing prior to generics. They work in coordination with the System.TypedReference struct.

There's also __arglist, which is used for variable length parameter lists.

One thing folks don't know much about is System.WeakReference -- a very useful class that keeps track of an object but still allows the garbage collector to collect it.

The most useful "hidden" feature would be the yield return keyword. It's not really hidden, but a lot of folks don't know about it. LINQ is built atop this; it allows for delay-executed queries by generating a state machine under the hood. Raymond Chen recently posted about the internal, gritty details.


ViewState getters can be one-liners.

Using a default value:

public string Caption
{
    get { return (string) (ViewState["Caption"] ?? "Foo"); }
    set { ViewState["Caption"] = value; }
}

public int Index
{
    get { return (int) (ViewState["Index"] ?? 0); }
    set { ViewState["Index"] = value; }
}

Using null as the default:

public string Caption
{
    get { return (string) ViewState["Caption"]; }
    set { ViewState["Caption"] = value; }
}

public int? Index
{
    get { return (int?) ViewState["Index"]; }
    set { ViewState["Index"] = value; }
}

This works for anything backed by a dictionary.


ThreadStaticAttribute is a favorite of mine. Also, NonSerializableAttribute is useful. (Can you tell I do a lot of server stuff using remoting?)


Attributes in general, but most of all DebuggerDisplay. Saves you years.


Lately I learned about the String.Join method. It is really useful when building strings like columns to select by a query.


Returning IQueryable projections

protected void LdsPostings_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{   
    var dc = new MyDataContext();
    var query = dc.Posting.AsQueryable();

    if (isCondition1)
    {
        query = query.Where(q => q.PostedBy == Username);
        e.Result = QueryProjection(query);
        return;
    }

    ...

    if (isConditionN)
    {
        query = query.Where(q => q.Status.StatusName == "submitted");
        query = query.Where(q => q.ReviewedBy == Username);
        e.Result = QueryProjection(query);
        return;
    }
}

and rather than coding the projection multiple times, create a single method:

private IQueryable QueryProjection(IQueryable<Posting> query)
{
    return query.Select(p => new
    {
        p.PostingID,
        p.Category.CategoryName,
        p.Type.TypeName,
        p.Status.StatusName,
        p.Description,
        p.Updated,
        p.PostedBy,
        p.ReviewedBy,
    });
}

Something I missed for a long time: you can compare strings with

"string".equals("String", StringComparison.InvariantCultureIgnoreCase)

instead of doing:

"string".ToLower() == "String".ToLower();

If you are trying to create a comma delimited string from a list of items:

string[] itemList = { "Example 1", "Example 2", "Example 3" };
CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();
commaStr.AddRange(itemList);
//outputs Example 1,Example 2,Example 3

Look here for another example.


A few hidden features I've come across:

  • stackalloc which lets you allocate arrays on the stack
  • Anonymous methods with no explicit parameter list, which are implicitly convertible to any delegate type with non-out/ref parameters (very handy for events, as noted in an earlier comment)
  • A lot of people aren't aware of what events really are (an add/remove pair of methods, like get/set for properties); field-like events in C# really declare both a variable and an event
  • The == and != operators can be overloaded to return types other than bool. Strange but true.
  • The query expression translation in C# 3 is really "simple" in some ways - which means you can get it to do some very odd things.
  • Nullable types have special boxing behaviour: a null value gets boxed to a null reference, and you can unbox from null to the nullable type too.

I think if you have to use nullable types, it's better to use Nullable<.T> rather than the question mark notation. It makes it eye-achingly obvious that magic is occurring. Not sure why anyone would ever want to use Nullable<.bool> though.

In a VB.NET Web service where the parameter might not be passed through (because the partners request wasn't consistent or reliable), but had to pass validation against the proposed type (Boolean for "if is search request"). Chalk it up to "another demand by management"...

...and yes, I know some people think it's not the right way to do these things, but IsSearchRequest As Nullable(Of Boolean) saved me losing my mind that night!


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.


The volatile keyword to tell the compiler that a field can be modified by multiple threads concurrently.


Definitely the Func<> types when used with statement lambdas in .NET 3.5. These allow customizable functions, and can be a great aid in offering user customizable objects without subclassing them or resorting to some limited system like keeping track of a variable that lists what button or key the user wants to monitor. Also, they can be called just like regular methods and can be assigned like variables. The only downside that I can think of is that you're limited to 5 arguments! Although by that point you might want to consider a different solution... Edit: Providing some examples.

...
public Func<InputHelper, float> _horizontalCameraMovement = (InputHelper input) => 
{
    return (input.LeftStickPosition.X * _moveRate) * _zoom;
}
public Func<InputHelper, float> _verticalCameraMovement = (InputHelper input) => 
{
    return (-input.LeftStickPosition.Y * _moveRate) * _zoom;
}
...
public void Update(InputHelper input)
{
    ...
    position += new Vector2(_horizontalCameraMovement(input), _verticalCameraMovement(input));
    ...
}

In this example, you can write a function that does arbitrary calculation and returns a float that will determine the amount that the camera moves by. Not the best code but it gets the point across.

private int foo;
public int FooProperty {
    get
    {
        if (_onFooGotten() == true)
            return _foo;
    }
    set
    {
        if (onFooSet() == true)
            _foo = value;
    }
}
...
public Func<bool> _onFooGotten = () => 
{
    //do whatever...
    return true;
}
public Func<bool> _onFooSet = () =>
{
    //do whatever...
    return true;
}

This isn't the best example (as I haven't really explored this use yet) but it shows an example of using a lambda function for a quick event raiser without the hassle of delegates. Edit: thought of another one. Nullables! The closest thing C# has to optional parameters.


I don't condone it, but I was surprised that goto is still around ducks incoming projectiles


Not sure if this one has been mentioned or not (11 pages!!)

But the OptionalField attribute for classes is amazing when you are versioning classes/objects that are going to be serialized.

http://msdn.microsoft.com/en-us/library/ms229752(VS.80).aspx


TryParse method for each primitive type is great when validating user input.

double doubleValue
if (!Double.TryParse(myDataRow("myColumn"), out doubleValue))
{
    // set validation error
}

One great class I like is System.Xml.XmlConvert which can be used to read values from xml tag. Especially, if I am reading a boolean value from xml attribute or element, I use

bool myFlag  = System.Xml.XmlConvert.ToBoolean(myAttribute.Value);

Note: since boolean type in xml accepts 1 and 0 in addition to "true" and "false" as valid values, using string comparison in this case is error-prone.


Static constructors.

Instances:

public class Example
{
    static Example()
    {
        // Code to execute during type initialization
    }

    public Example()
    {
        // Code to execute during object initialization
    }
}

Static classes:

public static class Example
{
    static Example()
    {
        // Code to execute during type initialization
    }
}

MSDN says:

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

For example:

public class MyWebService
{
    public static DateTime StartTime;

    static MyWebService()
    {
        MyWebService.StartTime = DateTime.Now;
    }

    public TimeSpan Uptime
    {
        get { return DateTime.Now - MyWebService.StartTime; }
    }
}

But, you could also just as easily have done:

public class MyWebService
{
    public static DateTime StartTime = DateTime.Now;

    public TimeSpan Uptime
    {
        get { return DateTime.Now - MyWebService.StartTime; }
    }
}

So you'll be hard-pressed to find any instance when you actually need to use a static constructor.

MSDN offers useful notes on static constructors:

  • A static constructor does not take access modifiers or have parameters.

  • A static constructor is called automatically to initialize the class before the first instance is created
    or any static members are referenced.

  • A static constructor cannot be called directly.

  • The user has no control on when the static constructor is executed in the program.

  • A typical use of static constructors is when the class is using a log file and the constructor is used to write
    entries to this file.

  • Static constructors are also useful when creating wrapper classes for
    unmanaged code, when the constructor
    can call the LoadLibrary method.

  • If a static constructor throws an exception, the runtime will not
    invoke it a second time, and the type will remain uninitialized for the
    lifetime of the application domain in which your program is running.

The most important note is that if an error occurs in the static constructor, a TypeIntializationException is thrown and you cannot drill down to the offending line of code. Instead, you have to examine the TypeInitializationException's InnerException member, which is the specific cause.


Returning anonymous types from a method and accessing members without reflection.

// Useful? probably not.
private void foo()
{
    var user = AnonCast(GetUserTuple(), new { Name = default(string), Badges = default(int) });
    Console.WriteLine("Name: {0} Badges: {1}", user.Name, user.Badges);
}

object GetUserTuple()
{
    return new { Name = "dp", Badges = 5 };
}    

// Using the magic of Type Inference...
static T AnonCast<T>(object obj, T t)
{
   return (T) obj;
}

I find the use of the conditional break function in Visual Studio very useful. I like the way it allows me to set the value to something that, for example can only be met in rare occasions and from there I can examine the code further.


A couple of things I like:

-If you create an interface similar to

 public interface SomeObject<T> where T : SomeObject<T>, new()

you force anything that inherits from this interface to contain a parameterless constructor. It is very useful for a couple of things I've run across.

-Using anonymous types to create a useful object on the fly:

var myAwesomeObject = new {Name="Foo", Size=10};

-Finally, many Java developers are familiar with syntax like:

public synchronized void MySynchronizedMethod(){}

However, in C# this is not valid syntax. The workaround is a method attribute:

 [MethodImpl(MethodImplOptions.Synchronized)]
 public void MySynchronizedMethod(){}

I especially like the nullable DateTime. So if you have some cases where a Date is given and other cases where no Date is given I think this is best to use and IMHO easier to understand as using DateTime.MinValue or anything else...

DateTime? myDate = null;

if (myDate.HasValue)
{
    //doSomething
}
else
{
    //soSomethingElse
}

My favorite trick is using the null coalesce operator and parentheses to automagically instantiate collections for me.

private IList<Foo> _foo;

public IList<Foo> ListOfFoo 
    { get { return _foo ?? (_foo = new List<Foo>()); } }

I'm late to this party, so my first choices are already taken. But I didn't see anyone mention this gem yet:

Parallel Extensions to the .NET Framework

It has things like replace with Parallel.For or foreach with Parallel.ForEach


Parallel Sample :
In your opinion, how many CLR object can be created in one second? enter image description here
See fallowing example :

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace ObjectInitSpeedTest
{
   class Program
   {
       //Note: don't forget to build it in Release mode.
       static void Main()
       {
           normalSpeedTest();           
           parallelSpeedTest();

           Console.ForegroundColor = ConsoleColor.White;
           Console.WriteLine("Press a key ...");
           Console.ReadKey();
       }

       private static void parallelSpeedTest()
       {
           Console.ForegroundColor = ConsoleColor.Yellow;
           Console.WriteLine("parallelSpeedTest");

           long totalObjectsCreated = 0;
           long totalElapsedTime = 0;

           var tasks = new List<Task>();
           var processorCount = Environment.ProcessorCount;

           Console.WriteLine("Running on {0} cores", processorCount);

           for (var t = 0; t < processorCount; t++)
           {
               tasks.Add(Task.Factory.StartNew(
               () =>
               {
                   const int reps = 1000000000;
                   var sp = Stopwatch.StartNew();
                   for (var j = 0; j < reps; ++j)
                   {
                       new object();
                   }
                   sp.Stop();

                   Interlocked.Add(ref totalObjectsCreated, reps);
                   Interlocked.Add(ref totalElapsedTime, sp.ElapsedMilliseconds);
               }
               ));
           }

           // let's complete all the tasks
           Task.WaitAll(tasks.ToArray());

           Console.WriteLine("Created {0:N} objects in 1 sec\n", (totalObjectsCreated / (totalElapsedTime / processorCount)) * 1000);
       }

       private static void normalSpeedTest()
       {
           Console.ForegroundColor = ConsoleColor.Green;
           Console.WriteLine("normalSpeedTest");

           const int reps = 1000000000;
           var sp = Stopwatch.StartNew();
           sp.Start();
           for (var j = 0; j < reps; ++j)
           {
               new object();
           }
           sp.Stop();

           Console.WriteLine("Created {0:N} objects in 1 sec\n", (reps / sp.ElapsedMilliseconds) * 1000);
       }
   }
}

I find it incredible what type of trouble the compiler goes through to sugar code the use of Outer Variables:

string output = "helo world!";
Action action = () => Console.WriteLine(output);
output = "hello!";
action();

This actually prints hello!. Why? Because the compiler creates a nested class for the delegate, with public fields for all outer variables and inserts setting-code before every single call to the delegate :) Here is above code 'reflectored':

Action action;
<>c__DisplayClass1 CS$<>8__locals2;
CS$<>8__locals2 = new <>c__DisplayClass1();
CS$<>8__locals2.output = "helo world!";
action = new Action(CS$<>8__locals2.<Main>b__0);
CS$<>8__locals2.output = "hello!";
action();

Pretty cool I think.


  1. I can't comment yet, but note that by default Visual Studio 2008 automatically steps over properties, so the DebuggerStepThrough attribute is no longer needed in that case.

  2. Also, I haven't noticed anyone showing how to declare a parameter-less lambda (useful for implementing Action<>)

    () => DoSomething(x);

You should also read up on closures - I'm not clever enough to explain them properly. But basically it means that the compiler does clever stuff so that the x in that line of code will still work even if it goes 'out of scope' after creating the lambda.

  1. I also discovered recently that you can pretend to ignore a lambda parameter:

    (e, _) => DoSomething(e)

It's not really ignoring it, it's just that _ is a valid identifier. So you couldn't ignore both of the parameters like that, but I think it is a kind of neat way to indicate that we don't care about that parameter (typically the EventArgs which is .Empty).


I didn't see this:

for (;;);

The same as

while (true) ;

With reference to the post w/ perma link "Hidden Features of C#?", there is another way to accomplish the same - indentation / line breaks. Check this out..

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.NewLineOnAttributes = true;
xmlWriterSettings.Indent = true;


XmlWriter xml = XmlWriter.Create(@"C:\file.xml", xmlWriterSettings);

// Start writing the data using xml.WriteStartElement(), xml.WriteElementString(...), xml.WriteEndElement() etc

I am not sure whether this is an unknown feature though!


Here is a new method of the string class in C# 4.0:

String.IsNullOrWhiteSpace(String value)

It's about time.


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".


This means T must have a public parameterless constructor :

 class MyClass<T> where T : new()
 {

 }

Use of @ before a string that contains escape char. Basically when a physical path is used to assign in a string variable everybody uses '\' where escape character is present in a string.

e.g. string strPath="D:\websites\web1\images\";

But escape characters can be ignored using @ before the string value.

e.g. string strPath=@"D:\websites\web1\images\";


Only for reference - enum binary operations using the extension method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace BinaryOpGenericTest
{
    [Flags]
    enum MyFlags
    {
        A = 1,
        B = 2,
        C = 4

    }

    static class EnumExtensions
    {
        private static Dictionary<Type, Delegate> m_operations = new Dictionary<Type, Delegate>();

        public static bool IsFlagSet<T>(this T firstOperand, T secondOperand) 
                                                  where T : struct
        {

            Type enumType = typeof(T);


            if (!enumType.IsEnum)
            {
                throw new InvalidOperationException("Enum type parameter required");
            }


            Delegate funcImplementorBase = null;
            m_operations.TryGetValue(enumType, out funcImplementorBase);

            Func<T, T, bool> funcImplementor = funcImplementorBase as Func<T, T, bool>;

            if (funcImplementor == null)
            {
                funcImplementor = buildFuncImplementor(secondOperand);
            }



            return funcImplementor(firstOperand, secondOperand);
        }


        private static Func<T, T, bool> buildFuncImplementor<T>(T val)
                                                            where T : struct
        {
            var first = Expression.Parameter(val.GetType(), "first");
            var second = Expression.Parameter(val.GetType(), "second");

            Expression convertSecondExpresion = Expression.Convert(second, typeof(int));
            var andOperator = Expression.Lambda<Func<T, T, bool>>(Expression.Equal(
                                                                                                       Expression.And(
                                                                                                            Expression.Convert(first, typeof(int)),
                                                                                                             convertSecondExpresion),
                                                                                                       convertSecondExpresion),
                                                                                             new[] { first, second });
            Func<T, T, bool> andOperatorFunc = andOperator.Compile();
            m_operations[typeof(T)] = andOperatorFunc;
            return andOperatorFunc;
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            MyFlags flag = MyFlags.A | MyFlags.B;

            Console.WriteLine(flag.IsFlagSet(MyFlags.A));            
            Console.WriteLine(EnumExtensions.IsFlagSet(flag, MyFlags.C));
            Console.ReadLine();
        }
    }
}

Don't know if this is a secret per se but I loved the added Enumerable (adds to IEnumerable) class in System.Linq.

http://msdn.microsoft.com/en-us/library/system.linq.enumerable_members.aspx

While the yield keyword is already listed. Iterator blocks are freaking amazing. I used them to build Lists that would be tested to see if they were co-prime. It basically allows you to go though a function that returns values one by one and stop any time.

Oh, I almost forgot the best class in the world when you can't optimize it any more. The BackgroundWorker!!!!

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx


Apologies for posting so late, I am new to Stack Overflow so missed the earlier opportunity.

I find that EventHandler<T> is a great feature of the framework that is underutilised.

Most C# developers I come across still define a custom event handler delegate when they are defining custom events, which is simply not necessary anymore.

Instead of:

public delegate void MyCustomEventHandler(object sender, MyCustomEventArgs e);

public class MyCustomEventClass 
{
    public event MyCustomEventHandler MyCustomEvent;
}

you can go:

public class MyCustomEventClass 
{
    public event EventHandler<MyCustomEventArgs> MyCustomEvent;
}

which is a lot more concise, plus you don't get into the dilemma of whether to put the delegate in the .cs file for the class that contains the event, or the EventArgs derived class.


Not sure Microsoft would like this question, especially with so many responses. I'm sure I once heard a Microsoft head say:

a hidden feature is a wasted feature

... or something to that effect.


Partial Methods

Charlie Calvert explains partial methods on his blog

Scott Cate has a nice partial method demo here

  1. Points of extensibility in Code Generated class (LINQ to SQL, EF)
  2. Does not get compiled into the dll if it is not implemented (check it out with .NET Reflector)

Not hidden, but I think that a lot of developers are not using the HasValue and Value properties on the nullable types.

        int? x = null;
        int y;
        if (x.HasValue)
            y = x.Value;

You can add and remove delegates with less typing.

Usual way:

handler += new EventHandler(func);

Less typing way:

handler += func;

Not sure why anyone would ever want to use Nullable<bool> though. :-)

True, False, FileNotFound?


Also useful, but not commonly used : Constrained Execution Regions.

A quote from BCL Team blog :

Constrained execution regions (CER's) exist to help a developer write her code to maintain consistency. The CLR doesn't guarantee that the developer's code is correct, but the CLR does hoist all of the runtime-induced failure points (ie, async exceptions) to either before the code runs, or after it has completed. Combined with constraints on what the developer can put in a CER, these are a useful way of making strong guarantees about whether your code will execute. CER's are eagerly prepared, meaning that when we see one, we will eagerly JIT any code found in its statically-discoverable call graph. If the CLR's host cares about stack overflow, we'll probe for some amount of stack space as well (though perhaps not enough stack space for any arbitrary method*). We also delay thread aborts until the CER has finished running.

It can be useful when making edits to more than one field of a data structure in an atomic fashion. So it helps to have transactions on objects.

Also CriticalFinalizerObject seems to be hidden(at least who are not writing unsafe code). A CriticalFinalizerObject guarantees that garbage collection will execute the finalizer. Upon allocation, the finalizer and its call graph are prepared in advance.


Expression to initialize a Dictionary in C# 3.5:

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


There are operators for performing implicit and explicit user-defined type conversion between the declared class and one or more arbitrary classes. The implicit operator effectively allows the simulation of overloading the assignement operator, which is possible in languages such as C++ but not C#.

It doesn't seem to be a feature one comes across very often, but it is in fact used in the LINQ to XML (System.Xml.Linq) library, where you can implicitly convert strings to XName objects. Example:

XName tagName = "x:Name";

I discovered this feature in this article about how to simulate multiple inheritance in C#.


Before lambda comes into play, it's anonymous delegate. That could be used for blanket code similar to Ruby's blockgiven. I haven't tested how lambda works though because I want to stick with .NET 2.0 so far.

For example when you want to make sure you remember to close your HTML tags:

MyHtmlWriter writer=new MyHtmlWriter();
writer.writeTag("html", 
  delegate ()
  { 
    writer.writeTag("head", 
       delegate() 
       { 
           writer.writeTag("title"...);
       }
    )
  })

I am sure if lambda is an option, that could yield much cleaner code :)


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.


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();
    }

This relates to static constructors. This is a method for performing static destruction (i.e. cleaning up resources when the program quits).

First off the class:

class StaticDestructor
{
    /// <summary>
    /// The delegate that is invoked when the destructor is called.
    /// </summary>
    public delegate void Handler();
    private Handler doDestroy;

    /// <summary>
    /// Creates a new static destructor with the specified delegate to handle the destruction.
    /// </summary>
    /// <param name="method">The delegate that will handle destruction.</param>
    public StaticDestructor(Handler method)
    {
        doDestroy = method;
    }

    ~StaticDestructor()
    {
        doDestroy();
    }
}

Then as a member of the class you wish to have a "static destructor" do:

private static readonly StaticDestructor destructor = new StaticDestructor
(
    delegate()
    {
        //Cleanup here
    }
);

This will now be called when final garbage collection occurs. This is useful if you absolutely need to free up certain resources.

A quick and dirty program exhibiting this behavior:

using System;

namespace TestStaticDestructor
{
    class StaticDestructor
    {
        public delegate void Handler();
        private Handler doDestroy;

        public StaticDestructor(Handler method)
        {
            doDestroy = method;
        }

        ~StaticDestructor()
        {
            doDestroy();
        }
    }

    class SomeClass
    {
        static SomeClass()
        {
            Console.WriteLine("Statically constructed!");
        }

        static readonly StaticDestructor destructor = new StaticDestructor(
            delegate()
            {
                Console.WriteLine("Statically destructed!");
            }
        );
    }

    class Program
    {
        static void Main(string[] args)
        {
            SomeClass someClass = new SomeClass();
            someClass = null;
            System.Threading.Thread.Sleep(1000);
        }
    }
}

When the program exits, the "static destructor" is called.


One interesting thing I've learned is that different parts of the framework and C# language were written at different times, hence inconsistencies. For example, the framework itself violates many FxCop rules because the rules weren't all in place when the framework was written.

Also, the using statement was intended for delinieating "scopes" and not specifically for disposing resources. It was written after the lock statement. Eric Gunnerson once mentioned something along the lines of that if the using statement came first, they might have not needed to write the lock statement (though who knows, maybe they would have anyways), because the using statement might have been sufficient.


I've read through all seven pages, and I'm missing these:

String.Join

I've seen a lot of for-loops to convert a list of items to a string with separators. It's always a pain to make sure you doin't start with a separator and don't end with a separator. A built-in method makes this easier:

String.Join(",", new String[] { "a", "b", "c"});

TODO in comment

Not really a C# feature, more of a Visual Studio feature. When you start your comment with TODO, it's added to your Visual Studio Task List (View -> Task List. Comments)

// TODO: Implement this!
throw new NotImplementedException();

Extension methods meets Generics

You can combine extension methods with Generics, when you think of the tip earlier in this topic, you can add extensions to specific interfaces

public static void Process<T>(this T item) where T:ITest,ITest2 {}

Enumerable.Range

Just want a list of integers?

Enumerable.Range(0, 15)

I'll try to think of some more...


Having read through all 9 pages of this I felt I had to point out a little unknown feature...

This was held true for .NET 1.1, using compression/decompression on gzipped files, one had to either:

  • Download ICSharpCode.ZipLib
  • Or, reference the Java library into your project and use the Java's in-built library to take advantage of the GZip's compression/decompression methods.

It is underused, that I did not know about, (still use ICSharpCode.ZipLib still, even with .NET 2/3.5) was that it was incorporated into the standard BCL version 2 upwards, in the System.IO.Compression namespace... see the MSDN page "GZipStream Class".


I just wanted to copy that code without the comments. So, the trick is to simply press the Alt button, and then highlight the rectangle you like.(e. g. below).

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //if (e.CommandName == "sel")
        //{
        //    lblCat.Text = e.CommandArgument.ToString();
        //}
    }

In the above code if I want to select :

e.CommandName == "sel"

lblCat.Text = e.Comman

Then I press ALt key and select the rectangle and no need to uncomment the lines.

Check this out.


The "TODO" property and the tasks list

//TODO: [something] 

Adding that to your code (the spacing is important) throws an item in your task list, and double clicking the item will jump you to the appropriate location in your code.


The generic event handler:

public event EventHandler<MyEventArgs> MyEvent;

This way you don't have to declare your own delegates all the time,


In dealing with interop between C++ and C#, many people don't realize that C++/CLI is a great option.

Say you have a C++ DLL and a C# DLL which depends on the C++ DLL. Often, the easiest technique is to compile some (or all) modules of the C++ DLL with the /clr switch. To have the C# call the C++ DLL is to write managed C++ wrapper classes in the C++ DLL. The C++/CLI classes can call the native C++ code much more seamlessly than C#, because the C++ compiler will automatically generate P/invokes for you, has a library specifically for interop, plus language features for interop like pin_ptr. And it allows managed and native code to coexist within the same binary.

On the C# side, you just call into the DLL as you would any other .NET binary.


I just found out about this one today -- and I've been working with C# for 5 years!

It's the namespace alias qualifier:

extern alias YourAliasHere;

You can use it to load multiple versions of the same type. This can be useful in maintenance or upgrade scenarios where you have an updated version of your type that won't work in some old code, but you need to upgrade it to the new version. Slap on a namespace alias qualifier, and the compiler will let you have both types in your code.


I like the EditorBrowsableAttribute. It lets you control whether a method/property is displayed or not in Intellisense. You can set the values to Always, Advanced, or Never.

From MSDN...

Remarks

EditorBrowsableAttribute is a hint to a designer indicating whether a property or method is to be displayed. You can use this type in a visual designer or text editor to determine what is visible to the user. For example, the IntelliSense engine in Visual Studio uses this attribute to determine whether to show a property or method.

In Visual C#, you can control when advanced properties appear in IntelliSense and the Properties Window with the Hide Advanced Members setting under Tools | Options | Text Editor | C#. The corresponding EditorBrowsableState is Advanced.


It's not actually a C# hidden feature, but I recently discovered the WeakReference class and was blown away by it (although this may be biased by the fact that it helped me found a solution to a particular problem of mine...)


I have often come across the need to have a generic parameter-object persisted into the viewstate in a base class.

public abstract class BaseListControl<ListType,KeyType,ParameterType>
                 : UserControl 
                 where ListType : BaseListType
                 && ParameterType : BaseParameterType, new
{

    private const string viewStateFilterKey = "FilterKey";

    protected ParameterType Filters
    {
        get
        {
            if (ViewState[viewStateFilterKey] == null)
                ViewState[viewStateFilterKey]= new ParameterType();

            return ViewState[viewStateFilterKey] as ParameterType;
        }
        set
        {
            ViewState[viewStateFilterKey] = value;
        }
    }

}

Usage:

private void SomeEventHappened(object sender, EventArgs e)
{
    Filters.SomeValue = SomeControl.SelectedValue;
}

private void TimeToFetchSomeData()
{
    GridView.DataSource = Repository.GetList(Filters);
}

This little trick with the "where ParameterType : BaseParameterType, new" is what makes it really work.

With this property in my baseclass, I can automate handling of paging, setting filter values to filter a gridview, make sorting really easy, etc.

I am really just saying that generics can be an enormously powerful beast in the wrong hands.


The Environment.UserInteractive property.

The UserInteractive property reports false for a Windows process or a service like IIS that runs without a user interface. If this property is false, do not display modal dialogs or message boxes because there is no graphical user interface for the user to interact with.


Ability to use LINQ Expressions to perform strongly-typed reflection:

static void Main(string[] args)
{
  var domain = "matrix";
  Check(() => domain);
  Console.ReadLine();
}

static void Check<T>(Expression<Func<T>> expr)
{
  var body = ((MemberExpression)expr.Body);
  Console.WriteLine("Name is: {0}", body.Member.Name);
  Console.WriteLine("Value is: {0}", ((FieldInfo)body.Member)
   .GetValue(((ConstantExpression)body.Expression).Value));
}

// output:
// Name is: 'domain'
// Value is: 'matrix'

More details are available at How to Find Out Variable or Parameter Name in C#?


I am so so late to this question, but I wanted to add a few that I don't think have been covered. These aren't C#-specific, but I think they're worthy of mention for any C# developer.

AmbientValueAttribute

This is similar to DefaultValueAttribute, but instead of providing the value that a property defaults to, it provides the value that a property uses to decide whether to request its value from somewhere else. For example, for many controls in WinForms, their ForeColor and BackColor properties have an AmbientValue of Color.Empty so that they know to get their colors from their parent control.

IsolatedStorageSettings

This is a Silverlight one. The framework handily includes this sealed class for providing settings persistence at both the per-application and per-site level.

Flag interaction with extension methods

Using extension methods, flag enumeration use can be a lot more readable.

    public static bool Contains(
          this MyEnumType enumValue,
          MyEnumType flagValue)
    {
        return ((enumValue & flagValue) == flagValue);
    }

    public static bool ContainsAny(
          this MyEnumType enumValue,
          MyEnumType flagValue)
    {
        return ((enumValue & flagValue) > 0);
    }

This makes checks for flag values nice and easy to read and write. Of course, it would be nicer if we could use generics and enforce T to be an enum, but that isn't allowed. Perhaps dynamic will make this easier.


I couldn't see this looking above - one that I didn't realise you could do until recently is to call one constructor from another:

class Example
{
    public Example(int value1)
        : this(value1, "Default Value")
    {
    }

    public Example(int value1, string value2)
    {
        m_Value1 = value1;
        m_value2 = value2;
    }

    int m_Value1;
    string m_value2;
}

Programmers moving from C/C++ may miss this one:

In C#, % (modulus operator) works on floats!


How about Expression Trees? They are the heart of LINQ and allow for defered execution:

Taken from David Hayden's blog:

In C# 3.0, you can define a delegate as follows using a lambda expression:

Func<int,int> f = x => x + 1;

This delegate is compiled into executable code in your application and can be called as such:

var three = f(2); // 2 + 1

The code works as you would expect. Nothing fancy here.

Expression Trees

When you define the delegate as an Expression Tree by using System.Query.Expression:

Expression<Func<int,int>> expression = x => x + 1;

The delegate is no longer compiled into executable code, but compiled as data that can be converted and compiled into the original delegate.

To actually use the delegate represented as an Expression Tree in your application, you would have to compile and invoke it in your application:

var originalDelegate = expression.Compile();

var three = originalDelegate.Invoke(2);

C# + CLR:

  1. Thread.MemoryBarrier: Most people wouldn't have used it and there is some inaccurate information on MSDN. But if you know intricacies then you can do nifty lock-free synchronization.

  2. volatile, Thread.VolatileRead, Thread.VolatileWrite: There are very very few people who gets the use of these and even fewer who understands all the risks they avoid and introduce :).

  3. ThreadStatic variables: There was only one situation in past few years I've found that ThreadStatic variables were absolutely god send and indispensable. When you want to do something for entire call chain, for example, they are very useful.

  4. fixed keyword: It's a hidden weapon when you want to make access to elements of large array almost as fast as C++ (by default C# enforces bound checks that slows down things).

  5. default(typeName) keyword can be used outside of generic class as well. It's useful to create empty copy of struct.

  6. One of the handy feature I use is DataRow[columnName].ToString() always returns non-null value. If value in database was NULL, you get empty string.

  7. Use Debugger object to break automatically when you want developer's attention even if s/he hasn't enabled automatic break on exception:


#if DEBUG  
    if (Debugger.IsAttached)  
        Debugger.Break();  
#endif
  1. You can alias complicated ugly looking generic types so you don't have to copy paste them again and again. Also you can make changes to that type in one place. For example,

    using ComplicatedDictionary = Dictionary<int, Dictionary<string, object>>;
    ComplicatedDictionary myDictionary = new ComplicatedDictionary();

Unions (the C++ shared memory kind) in pure, safe C#

Without resorting to unsafe mode and pointers, you can have class members share memory space in a class/struct. Given the following class:

[StructLayout(LayoutKind.Explicit)]
public class A
{
    [FieldOffset(0)]
    public byte One;

    [FieldOffset(1)]
    public byte Two;

    [FieldOffset(2)]
    public byte Three;

    [FieldOffset(3)]
    public byte Four;

    [FieldOffset(0)]
    public int Int32;
}

You can modify the values of the byte fields by manipulating the Int32 field and vice-versa. For example, this program:

    static void Main(string[] args)
    {
        A a = new A { Int32 = int.MaxValue };

        Console.WriteLine(a.Int32);
        Console.WriteLine("{0:X} {1:X} {2:X} {3:X}", a.One, a.Two, a.Three, a.Four);

        a.Four = 0;
        a.Three = 0;
        Console.WriteLine(a.Int32);
    }

Outputs this:

2147483647
FF FF FF 7F
65535

just add using System.Runtime.InteropServices;


Need to return an empty IEnumerable?

public IEnumerable<T> GetEnumerator(){
  yield break;
}

Aliased generics:

using ASimpleName = Dictionary<string, Dictionary<string, List<string>>>;

It allows you to use ASimpleName, instead of Dictionary<string, Dictionary<string, List<string>>>.

Use it when you would use the same generic big long complex thing in a lot of places.


Easily determine type with which variable was declared (from my answer):

using System;
using System.Collections.Generic;

static class Program
{
    public static Type GetDeclaredType<T>(T x)
    {
        return typeof(T);
    }

    // Demonstrate how GetDeclaredType works
    static void Main(string[] args)
    {
        IList<string> iList = new List<string>();
        List<string> list = null;

        Console.WriteLine(GetDeclaredType(iList).Name);
        Console.WriteLine(GetDeclaredType(list).Name);
    }
}

Results:

IList`1
List`1

And its name (borrowed from "Get variable name"):

static void Main(string[] args)
{
    Console.WriteLine("Name is '{0}'", GetName(new {args}));
    Console.ReadLine();
}

static string GetName<T>(T item) where T : class
{
    var properties = typeof(T).GetProperties();
    return properties[0].Name;
}

Result: Name is 'args'


Saw a mention of List.ForEach above; 2.0 introduced a bevy of predicate-based collection operations - Find, FindAll, Exists, etc. Coupled with anonymous delegates you can almost achieve the simplicity of 3.5's lambda expressions.


Using "~" operator with FlagAttribute and enum
Sometime we would use Flag attribute with enum to perform bitwise manipulation on the enumeration.

 [Flags]
 public enum Colors
 {
    None  = 0,
    Red   = 1,
    Blue  = 2,
    White = 4,
    Black = 8,
    Green = 16,
    All   = 31 //It seems pretty bad...
 }

Notice that, the value of option "All" which in enum is quite strange.
Instead of that we can use "~" operator with flagged enum.

 [Flags]
 public enum Colors
 {
    None  = 0,
    Red   = 1,
    Blue  = 2,
    White = 4,
    Black = 8,
    Green = 16,
    All   = ~0 //much better now. that mean 0xffffffff in default.
 }

double dSqrd = Math.Pow(d,2.0); 

is more accurate than

double dSqrd = d * d; // Here we can lose precision

You can limit the life and thus scope of variables by using { } brackets.

{
    string test2 = "3";
    Console.Write(test2);
}

Console.Write(test2); //compile error

test2 only lives within the brackets.


I am bit late in this conversation and I would like to contribute the following. It may be a new thing for some developers.

public class User
{
    public long UserId { get; set; }
    public String Name { get; set; }
    public String Password { get; set; }
    public String Email { get; set; }
}

The usual way to declare and initialize it is with a constructor or like following.

User user = new User();
user.UserId = 1;
user.Name = "myname";
etc

But I learned following way to initialize it. I know Visual Basic developers will love it because it's like with operator available only in VB.NET and not in C# that is as follows.

User user = new User()
{
    UserId = 1,
    Name = "myname",
    Email = "[email protected]",
    Password = "mypassword"
};

Lambda Expressions

Func<int, int, int> add = (a, b) => (a + b);

Obscure String Formats

Console.WriteLine("{0:D10}", 2); // 0000000002

Dictionary<string, string> dict = new Dictionary<string, string> { 
    {"David", "C#"}, 
    {"Johann", "Perl"}, 
    {"Morgan", "Python"}
};

Console.WriteLine( "{0,10} {1, 10}", "Programmer", "Language" );

Console.WriteLine( "-".PadRight( 21, '-' ) );

foreach (string key in dict.Keys)
{
    Console.WriteLine( "{0, 10} {1, 10}", key, dict[key] );             
}

Arbitrary nested scopes { }


1. For finer scoping behaviour

{ anywhere inside members }, { using only braces }, { with no control statement }.

void MyWritingMethod() {

    int sameAge = 35;


    { // scope some work
        string name = "Joe";
        Log.Write(name + sameAge.ToString());
    }


    { // scope some other work
        string name = "Susan";
        Log.Write(name + sameAge.ToString());
    }

    // I'll never mix up Joe and Susan again
}

Inside large, confusing or archaic members (not that they should ever exist, however,) it helps me prevent against using wrong variable names. Scope stuff to finer levels.

2. For code beautification or visual semantics

For example, this XML writing code follows the indentation level of the actual generated XML (i.e. Visual Studio will indent the scoping braces accordingly)

XmlWriter xw = new XmlWriter(..);

//<root>
xw.WriteStartElement("root");
{
    //<game>
    xw.WriteStartElement("game");
    {
        //<score>#</score>
        for (int i = 0; i < scores.Length; ++i) // multiple scores
            xw.WriteElementString("score", scores[i].ToString());

    }
    //</game>
    xw.WriteEndElement();
}
//</root>
xw.WriteEndElement();

3. Mimic a 'with' statement

(Also another use to keep temp work out of the main scope)
Provided by Patrik: sometimes used to mimic the VB "with-statement" in C#.

var somePerson = this.GetPerson();  // whatever 
{ 
    var p = somePerson; 
    p.FirstName = "John"; 
    p.LastName = "Doe"; 
    //... 
    p.City = "Gotham"; 
} 

For the discerning programmer.


Accessing local variables from anonymous methods allows you to wrap just about any code with new control flow logic, without having to factor out that code into another method. Local variables declared outside the method are available inside the method such as the endOfLineChar local variable in the example here:

http://aaronls.wordpress.com/2010/02/02/retrying-on-exception-conditionally/


Not hidden, but pretty neat. I find this a more succinct substitute for a simple if-then-else that just assigns a value based on a condition.

string result = 
              i < 2 ?               //question
              "less than 2" :       //answer
              i < 5 ?               //question
             "less than 5":         //answer   
              i < 10 ?              //question
              "less than 10":       //answer
              "something else";     //default answer 

The extern alias keyword to reference two versions of assemblies that have the same fully-qualified type names.


I just want to mention (because of the OP metioning where T : struct) that one of the C# compiler gotchas is that

where T : Enum

will NOT compile. It throws the error "Constraint cannot be special class 'System.Enum'".


I love the fact that I can use LINQ to objects on plain old .NET 2.0 (i.e. without requiring .NET 3.5 to be installed everywhere). All you need is an implementation of all the query operator Extension methods - see LINQBridge


This trick for calling private methods using Delegate.CreateDelegate is extremely neat.

var subject = new Subject();
var doSomething = (Func<String, String>)
    Delegate.CreateDelegate(typeof(Func<String, String>), subject, "DoSomething");
Console.WriteLine(doSomething("Hello Freggles"));

Here's a context where it's useful


I call this AutoDebug because you can drop right into debug where and when you need based on a bool value which could also be stored as a project user setting as well.

Example:

//Place at top of your code
public UseAutoDebug = true;


//Place anywhere in your code including catch areas in try/catch blocks
Debug.Assert(!this.UseAutoDebug);

Simply place the above in try/catch blocks or other areas of your code and set UseAutoDebug to true or false and drop into debug anytime you wish for testing.

You can leave this code in place and toggle this feature on and off when testing, You can also save it as a Project Setting, and manually change it after deployment to get additional bug information from users when/if needed as well.

You can see a functional and working example of using this technique in this Visual Studio C# Project Template here, where it is used heavily:

http://code.msdn.microsoft.com/SEHE


Being able to have enum types have values other than int (the default)

public enum MyEnum : long
{
    Val1 = 1,
    Val2 = 2
}

Also, the fact that you can assign any numeric value to that enum:

MyEnum e = (MyEnum)123;

Type-inference for factory methods

I don't know if this has been posted already (I scanned the first post, couldn't find it).

This is best shown with an example, assuming you have this class (to simulate a tuple), in in an attempt to demonstrate all the language features that make this possible I will go through it step by step.

public class Tuple<V1, V2> : Tuple
{
    public readonly V1 v1;
    public readonly V2 v2;

    public Tuple(V1 v1, V2 v2)
    {
      this.v1 = v1;
      this.v2 = v2;
    }
}

Everyone knows how to create an instance of it, such as:

Tuple<int, string> tup = new Tuple<int, string>(1, "Hello, World!");

Not exactly rocket science, now we can of course change the type declaration of the variable to var, like this:

var tup = new Tuple<int, string>(1, "Hello, World!");

Still well known, to digress a bit here's a static method with type parameters, which everyone should be familiar with:

public static void Create<T1, T2>()
{
    // stuff
}

Calling it is, again common knowledge, done like this:

Create<float, double>();

What most people don't know is that if the arguments to the generic method contains all the types it requires they can be inferred, for example:

public static void Create<T1, T2>(T1 a, T2 b)
{
    // stuff
}

These two calls are identical:

Create<float, string>(1.0f, "test");
Create(1.0f, "test");

Since T1 and T2 is inferred from the arguments you passed. Combining this knowledge with the var keyword, we can by adding a second static class with a static method, such as:

public abstract class Tuple
{
    public static Tuple<V1, V2> Create<V1, V2>(V1 v1, V2 v2)
    {
        return new Tuple<V1, V2>(v1, v2);
    }
}

Achieve this effect:

var tup = Tuple.Create(1, "Hello, World!");

This means that the types of the: variable "tup", the type-parameters of "Create" and the return value of "Create" are all inferred from the types you pass as arguments to Create

The full code looks something like this:

public abstract class Tuple
{
    public static Tuple<V1, V2> Create<V1, V2>(V1 v1, V2 v2)
    {
        return new Tuple<V1, V2>(v1, v2);
    }
}

public class Tuple<V1, V2> : Tuple
{
    public readonly V1 v1;
    public readonly V2 v2;

    public Tuple(V1 v1, V2 v2)
    {
        this.v1 = v1;
        this.v2 = v2;
    }
}

// Example usage:
var tup = Tuple.Create(1, "test");

Which gives you fully type inferred factory methods everywhere!


I like looking up stuff in a list like:-

bool basketContainsFruit(string fruit) {
  return new[] { "apple", "orange", "banana", "pear" }.Contains(fruit);
}

Rather than:-

bool basketContainsFruit(string fruit) {
  return fruit == "apple" || fruit == "orange" || fruit == "banana" ||
    fruit == "pear";
}

Doesn't come up that much in practice, but the idea of matching items against the subject of the search can be really quite useful + succinct.


A couple other attributes from the System.Diagnostics namespace are quite helpful.

DebuggerBrowsable will let you hide variables from the debugger window (we use it for all private backing variables of exposed properties). Along with that, DebuggerStepThrough makes the debugger step over that code, very useful for dumb properties (probably should be converted to auto-properties if you can take a dependency to the C# 3.0 compiler). As an example

[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string nickName;
public string NickName    {
    [DebuggerStepThrough]
    get { return nickName; }
    [DebuggerStepThrough]
    set { this.nickName = value; }
}

What about IObservable?

Pretty much everybody knows IEnumerable but their mathematical dual seems to be unknown IObservable. Maybe because its new in .NET 4.

What it does is instead of pulling the information (like an enumerable) it pushes information to the subscriber(s) of the observerable.

Together with the Rx extensions it will change how we deal with events. Just to illustrate how powerful it is check a very short example here.


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.


  • TransactionScope and DependentTransaction in System.Transactions is a lightweight way to use transaction processing in .NET - it's not just for Database transactions either
  • String.IsNullOrEmpty is one that I am surprised to learn a lot of developers don't know about
  • List.ForEach - iterate through your generic list using a delegate method

There are more, but that is the three obvious ones of the top of my head...


This may be pretty basic to database application developers, but it took me a while to realize that null is not the same as DBNull.value.

You have to use DBNull.value when you want to see if a value from a database record is null.


I didn't knew about Generic methods which could help avoid using Method Overloadding. Below are overloaded methods to print int and double numbers.

    private static void printNumbers(int [] intNumbers)
    { 
        foreach(int element in intNumbers)
        {
            Console.WriteLine(element);
        }

    }

    private static void printNumbers(double[] doubleNumbers)
    {
        foreach (double element in doubleNumbers)
        {
            Console.WriteLine(element);
        }
    }

Generic method which help to have one method for both of the above

    private static void printNumbers<E>(E [] Numbers)
    {
        foreach (E element in Numbers)
        {
            Console.WriteLine(element);
        }
    }

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.


"yield" would come to my mind. Some of the attributes like [DefaultValue()] are also among my favorites.

The "var" keyword is a bit more known, but that you can use it in .NET 2.0 applications as well (as long as you use the .NET 3.5 compiler and set it to output 2.0 code) does not seem to be known very well.

Edit: kokos, thanks for pointing out the ?? operator, that's indeed really useful. Since it's a bit hard to google for it (as ?? is just ignored), here is the MSDN documentation page for that operator: ?? Operator (C# Reference)


I was reading thru the book "Pro ASP.NET MVC Framework" (APress) and observed something the author was doing with a Dictionary object that was foreign to me.

He added a new Key/Value Pair without using the Add() method. He then overwrote that same Key/Value pair without having to check if that key already existed. For example:

Dictionary<string, int> nameAgeDict = new Dictionary<string, int>();
nameAgeDict["Joe"] = 34;      // no error. will just auto-add key/value
nameAgeDict["Joe"] = 41;      // no error. key/value just get overwritten
nameAgeDict.Add("Joe", 30);   // ERROR! key already exists

There are many cases where I don't need to check if my Dictionary already has a key or not and I just want to add the respective key/value pair (overwriting the existing key/value pair, if necessary.) Prior to this discovery, I would always have to check to see if the key already existed before adding it.


I think one of the most under-appreciated and lesser-known features of C# (.NET 3.5) are Expression Trees, especially when combined with Generics and Lambdas. This is an approach to API creation that newer libraries like NInject and Moq are using.

For example, let's say that I want to register a method with an API and that API needs to get the method name

Given this class:

public class MyClass
{
     public void SomeMethod() { /* Do Something */ }
}

Before, it was very common to see developers do this with strings and types (or something else largely string-based):

RegisterMethod(typeof(MyClass), "SomeMethod");

Well, that sucks because of the lack of strong-typing. What if I rename "SomeMethod"? Now, in 3.5 however, I can do this in a strongly-typed fashion:

RegisterMethod<MyClass>(cl => cl.SomeMethod());

In which the RegisterMethod class uses Expression<Action<T>> like this:

void RegisterMethod<T>(Expression<Action<T>> action) where T : class
{
    var expression = (action.Body as MethodCallExpression);

    if (expression != null)
    {
        // TODO: Register method
        Console.WriteLine(expression.Method.Name);
    }
}

This is one big reason that I'm in love with Lambdas and Expression Trees right now.


The C# ?? null coalescing operator -

Not really hidden, but rarely used. Probably because a lot of developers run a mile when they see the conditional ? operator, so they run two when they see this one. Used:

string mystring = foo ?? "foo was null"

rather than

string mystring;
if (foo==null)
    mystring = "foo was null";
else
    mystring = foo;

Width in string.Format()

Console.WriteLine("Product: {0,-7} Price: {1,5}", product1, price1);
Console.WriteLine("Product: {0,-7} Price: {1,5}", product2, price2);

produces

alt text

from Prabir's Blog | Hidden C# feature


I found that only few developers know about this feature.

If you need a method that works with a value-type variable via some interface (implemented by this value type), it's easy to avoid boxing during the method call.

Example code:

using System;
using System.Collections;

interface IFoo {
    void Foo();
}
struct MyStructure : IFoo {
    public void Foo() {
    }
}
public static class Program {
    static void MethodDoesNotBoxArguments<T>(T t) where T : IFoo {
        t.Foo();
    }
    static void Main(string[] args) {
        MyStructure s = new MyStructure();
        MethodThatDoesNotBoxArguments(s);
    }
}

IL code doesn't contain any box instructions:

.method private hidebysig static void  MethodDoesNotBoxArguments<(IFoo) T>(!!T t) cil managed
{
  // Code size       14 (0xe)
  .maxstack  8
  IL_0000:  ldarga.s   t
  IL_0002:  constrained. !!T
  IL_0008:  callvirt   instance void IFoo::Foo()
  IL_000d:  ret
} // end of method Program::MethodDoesNotBoxArguments

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       15 (0xf)
  .maxstack  1
  .locals init ([0] valuetype MyStructure s)
  IL_0000:  ldloca.s   s
  IL_0002:  initobj    MyStructure
  IL_0008:  ldloc.0
  IL_0009:  call       void Program::MethodDoesNotBoxArguments<valuetype MyStructure>(!!0)
  IL_000e:  ret
} // end of method Program::Main

See Richter, J. CLR via C#, 2nd edition, chapter 14: Interfaces, section about Generics and Interface Constraints.

See also my answer to another question.


The params keyword, i.e.

public void DoSomething(params string[] theStrings)
{
  foreach(string s in theStrings)
  {
    // Something with the Strings…
  }
}

Called like

DoSomething(“The”, “cat”, “sat”, “on”, “the” ,”mat”);

When debugging, you can type $exception in the Watch\QuickWatch\Immediate window and get all the info on the exception of the current frame. This is very useful if you've got 1st chance exceptions turned on!


__arglist as well

[DllImport("msvcrt40.dll")]
public static extern int printf(string format, __arglist);

static void Main(string[] args)
{
   printf("Hello %s!\n", __arglist("Bart"));
}

Nesting Using Statements

Usually we do it like this:

StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter()) {
    using (IndentedTextWriter itw = new IndentedTextWriter(sw)) {
        ... 
    }
}

But we can do it this way:

StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter())
using (IndentedTextWriter itw = new IndentedTextWriter(sw)) {
    ... 
}

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


You can combine the protected and internal accessor to make it public within the same assembly, but protected in a diffrent assembly. This can be used on fields, properties, method and even constants.


The Or assignment operator is quite nice. You can write this:

x |= y

instead of this:

x = x | y

This is often practical if you have to a variable or property (x in the example) that starts out as false but you want to change it to the value of some other boolean variable/property only when that other value is true.


TrueForAll Method of List<T> :

List<int> s = new List<int> { 6, 1, 2 };

bool a = s.TrueForAll(p => p > 0);

Just learned the joys of [UnmanagedFunctionPointerAttribute(CallingConvention.CDecl)] from trying to interface with an unmanaged C++ function library that defined callbacks without __stdcall.


More of a runtime feature, but I recently learned that there are two garbage collectors. The workstation gc and the server gc. Workstation is the default on client versions of windows, but server is much faster on multicore machines.


<configuration>
   <runtime>
      <gcServer enabled="true"/>
   </runtime>
</configuration>

Be careful. The server gc requires more memory.


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;

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.


If you want to prevent the garbage collector from running the finalizer of an object, just use GC.SuppressFinalize(object);. In a similar vein, GC.KeepAlive(object); will prevent the garbage collector from collecting that object by referencing it. Not very commonly used, at least in my experience, but nice to know just in case.


When defining custom attributes you can use them with [MyAttAttribute] or with [MyAtt]. When classes exist for both writings, then a compilation error occures.

The @ special character can be used to distinguish between them:

[AttributeUsage(AttributeTargets.All)]
public class X: Attribute
{}

[AttributeUsage(AttributeTargets.All)]
public class XAttribute: Attribute
{}

[X]      // Error: ambiguity
class Class1 {}

[XAttribute]   // Refers to XAttribute
class Class2 {}

[@X]      // Refers to X
class Class3 {}

[@XAttribute]   // Refers to XAttribute
class Class4 {}

@Brad Barker

I think if you have to use nullable types, it's better to use Nullable<.T> rather than the question mark notation. It makes it eye-achingly obvious that magic is occurring. Not sure why anyone would ever want to use Nullable<.bool> though. :-)

Krzysztof Cwalina (one of the authors of Framwork Design Guidlines) has a good post here: http://blogs.msdn.com/kcwalina/archive/2008/07/16/Nullable.aspx

And Mike Hadlow has a nice post on Nullability Voodoo


JavaScript-like anonymous inline-functions

Return a String:

var s = new Func<String>(() =>
{
    return "Hello World!";
})();

Return a more complex Object:

var d = new Func<Dictionary<Int32, String>>(() =>
{
    return new Dictionary<Int32, String>
    {
        { 0, "Foo" },
        { 1, "Bar" },
        { 2, "..." }
    };
})();

A real-world use-case:

var tr = new TableRow();

tr.Cells.AddRange
(
    new[]
    {
        new TableCell { Text = "" },
        new TableCell { Text = "" },
        new TableCell { Text = "" },

        new TableCell
        {
            Text = new Func<String>(() =>
            {
                return @"Result of a chunk of logic, without having to define
                         the logic outside of the TableCell constructor";
            })()
        },

        new TableCell { Text = "" },
        new TableCell { Text = "" }
    }
);

Note: You cannot re-use variable names inside the inline-function's scope.


Alternative syntax

// The one-liner
Func<Int32, Int32, String> Add = (a, b) => Convert.ToString(a + b);

// Multiple lines
Func<Int32, Int32, String> Add = (a, b) =>
{
    var i = a + b;

    return i.ToString();
};

// Without parameters
Func<String> Foo = () => "";

// Without parameters, multiple lines
Func<String> Foo = () =>
{
    return "";
};

Shorten a string and add horizontal ellipsis...

Func<String, String> Shorten = s => s.Length > 100 ? s.Substring(0, 100) + "&hellip;" : s;

Well... Don't use it, but a lot of people don't know C# supports the evil goto:)

static void Example()
{
    int i = 0;
top:
    Console.WriteLine(i.ToString());
    if (i == 0)
    {
        i++;
        goto top;
    }
}

@Ed, I'm a bit reticent about posting this as it's little more than nitpicking. However, I would point out that in your code sample:

MyClass c;
  if (obj is MyClass)
    c = obj as MyClass

If you're going to use 'is', why follow it up with a safe cast using 'as'? If you've ascertained that obj is indeed MyClass, a bog-standard cast:

c = (MyClass)obj

...is never going to fail.

Similarly, you could just say:

MyClass c = obj as MyClass;
if(c != null)
{
   ...
}

I don't know enough about .NET's innards to be sure, but my instincts tell me that this would cut a maximum of two type casts operations down to a maximum of one. It's hardly likely to break the processing bank either way; personally, I think the latter form looks cleaner too.


Dictionary.TryGetValue(K key, out V value)

Works as a check and a get in one. Rather than;

if(dictionary.ContainsKey(key)) 
{
    value = dictionary[key];
    ...
}

you can just do;

if(dictionary.TryGetValue(key, out value)) 
{ ... }

and the value has been set.


String interning. This is one that I haven't seen come up in this discussion yet. It's a little obscure, but in certain conditions it can be useful.

The CLR keeps a table of references to literal strings (and programmatically interned strings). If you use the same string in several places in your code it will be stored once in the table. This can ease the amount of memory required for allocating strings.

You can test if a string is interned by using String.IsInterned(string) and you can intern a string using String.Intern(string).

Note: The CLR can hold a reference to an interned string after application or even AppDomain end. See the MSDN documentation for details.


Having just learned the meaning of invariance, covariance and contravariance, I discovered the in and out generic modifiers that will be included in .NET 4.0. They seem obscure enough that most programmers would not know about them.

There's an article at Visual Studio Magazine which discusses these keywords and how they will be used.


@David in Dakota:

Console.WriteLine( "-".PadRight( 21, '-' ) );

I used to do this, until I discovered that the String class has a constructor that allows you to do the same thing in a cleaner way:

new String('-',22);

The @ tells the compiler to ignore any escape characters in a string.

Just wanted to clarify this one... it doesn't tell it to ignore the escape characters, it actually tells the compiler to interpret the string as a literal.

If you have

string s = @"cat
             dog
             fish"

it will actually print out as (note that it even includes the whitespace used for indentation):

cat
             dog
             fish

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
}

Two things I like are Automatic properties so you can collapse your code down even further:

private string _name;
public string Name
{
    get
    {
        return _name;
    }
    set
    {
        _name = value;
    }
}

becomes

public string Name { get; set;}

Also object initializers:

Employee emp = new Employee();
emp.Name = "John Smith";
emp.StartDate = DateTime.Now();

becomes

Employee emp = new Employee {Name="John Smith", StartDate=DateTime.Now()}

Ability to create instance of the type based on the generic parameter like this

new T();


AppDomain.UnhandledException Event is also candidate for being hidden.

This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application. If sufficient information about the state of the application is available, other actions may be undertaken — such as saving program data for later recovery. Caution is advised, because program data can become corrupted when exceptions are not handled.

We can see, even on this site, a lot of people are wondering why their application is not starting, why it crashed, etc. The AppDomain.UnhandledException event can be very useful for such cases as it provides the possibility at least to log the reason of application failure.


Literals can be used as variables of that type. eg.

Console.WriteLine(5.ToString());
Console.WriteLine(5M.GetType());   // Returns "System.Decimal"
Console.WriteLine("This is a string!!!".Replace("!!", "!"));

Just a bit of trivia...

There's quite a few things people haven't mentioned, but they have mostly to do with unsafe constructs. Here's one that can be used by "regular" code though:

The checked/unchecked keywords:

public static int UncheckedAddition(int a, int b)
{
    unchecked { return a + b; }
}

public static int CheckedAddition(int a, int b)
{
    checked { return a + b; } // or "return checked(a + b)";
}

public static void Main() 
{
    Console.WriteLine("Unchecked: " + UncheckedAddition(Int32.MaxValue, + 1));  // "Wraps around"
    Console.WriteLine("Checked: " + CheckedAddition(Int32.MaxValue, + 1));  // Throws an Overflow exception
    Console.ReadLine();
}

You can put several attributes in one pair of square brackets:

    [OperationContract, ServiceKnownType(typeof(Prism)), ServiceKnownType(typeof(Cuboid))]
    Shape GetShape();

Here's a useful one for regular expressions and file paths:

"c:\\program files\\oldway"
@"c:\program file\newway"

The @ tells the compiler to ignore any escape characters in a string.


Keeps DataGridView from showing the property:

[System.ComponentModel.Browsable(false)]
public String LastActionID{get; private set;}

Lets you set a friendly display for components (like a DataGrid or DataGridView):

[System.ComponentModel.DisplayName("Last Action")]
public String LastAction{get; private set;}

For your backing variables, if you don't want anything accessing them directly this makes it tougher:

[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
    private DataController p_dataSources;

I couldn't figure out what use some of the functions in the Convert class had (such as Convert.ToDouble(int), Convert.ToInt(double)) until I combined them with Array.ConvertAll:

int[] someArrayYouHaveAsInt;
double[] copyOfArrayAsDouble = Array.ConvertAll<int, double>(
                                someArrayYouHaveAsInt,
                                new Converter<int,double>(Convert.ToDouble));

Which avoids the resource allocation issues that arise from defining an inline delegate/closure (and slightly more readable):

int[] someArrayYouHaveAsInt;
double[] copyOfArrayAsDouble = Array.ConvertAll<int, double>(
                                someArrayYouHaveAsInt,
                                new Converter<int,double>(
                                  delegate(int i) { return (double)i; }
                                ));

Don't forget about goto.


The 'default' keyword in generic types:

T t = default(T);

results in a 'null' if T is a reference type, and 0 if it is an int, false if it is a boolean, etcetera.


Is constructor chain already cited?

namespace constructorChain {
    using System;

    public class Class1 {
        public string x;
        public string y;

        public Class1() {
            x = "class1";
            y = "";
        }

        public Class1(string y)
            : this() {
            this.y = y;
        }
    }

    public class Class2 : Class1 {
        public Class2(int y)
            : base(y.ToString()) {

        }
    }
}

...

        constructorChain.Class1 c1 = new constructorChain.Class1();
        constructorChain.Class1 c12 = new constructorChain.Class1("Hello, Constructor!");
        constructorChain.Class2 c2 = new constructorChain.Class2(10);
        Console.WriteLine("{0}:{1}", c1.x, c1.y);
        Console.WriteLine("{0}:{1}", c12.x, c12.y);
        Console.WriteLine("{0}:{1}", c2.x, c2.y);

        Console.ReadLine();

One of the most useful features Visual Studio has is "Make object id". It generates an id and "attaches" to the object so wherever you look at the object you will also see the id (regardless of the thread).

While debugging right click on the variable tooltip and there you have it. It also works on watched/autos/locals variables.


You type "prop" and then press [TAB] twice, it generates useful code for your properties and can speed your typing.

I know this works in VS 2005 (I use it) but I don´t know in previous versions.


System.Runtime.Remoting.Proxies.RealProxy

It enables Aspect Oriented Programming in C#, and you can also do a lot of other fancy stuff with it.


At first - DebuggerTypeProxy.

[DebuggerTypeProxy(typeof(HashtableDebugView))]
class MyHashtable : Hashtable
{
    private const string TestString = 
        "This should not appear in the debug window.";

    internal class HashtableDebugView
    {
        private Hashtable hashtable;
        public const string TestStringProxy = 
            "This should appear in the debug window.";

        // The constructor for the type proxy class must have a 
        // constructor that takes the target type as a parameter.
        public HashtableDebugView(Hashtable hashtable)
        {
            this.hashtable = hashtable;
        }
    }
}

At second:

ICustomTypeDescriptor


typedefs

Someone posted that they miss typedefs but you can do it like this

using ListOfDictionary = System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>>;

and declare it as

ListOfDictionary list = new ListOfDictionary();

I'm becoming a big fan of extension methods since they can add much wanted functionality to existing code or code you can't edit. One of my favorites I add in to everything I do now is for string.IsNullOrEmpty()

public static class Strings
{
    public static bool IsNullOrEmpty(this string value)
    {
        return string.IsNullOrEmpty(value);
    }
}

This lets you shorten your code a bit like this

var input = Console.ReadLine();
if (input.IsNullOrEmpty())
{
    Console.WriteLine("try again");
}

Generic constraints:

 //Constructor constraint, T has a default empty constructor
class Node<K,T> where T : new() 
{
}

//Reference\Value Type constraints
//T is a struct
public class MyClass<T> where T : struct 

{...}

//T is a reference type
public class MyClass<T> where T : class 

{...}

public class MyClass<T> where T : SomeBaseClass, ISomeInterface 

{...}

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.

This isn't a C# specific feature but it is an addon that I find very useful. It is called the Resource Refactoring Tool. It allows you to right click on a literal string and extract it into a resource file. It will search the code and find any other literal strings that match and replace it with the same resource from the Resx file.

http://www.codeplex.com/ResourceRefactoring


lambdas and type inference are underrated. Lambdas can have multiple statements and they double as a compatible delegate object automatically (just make sure the signature match) as in:

Console.CancelKeyPress +=
    (sender, e) => {
        Console.WriteLine("CTRL+C detected!\n");
        e.Cancel = true;
    };

Note that I don't have a new CancellationEventHandler nor do I have to specify types of sender and e, they're inferable from the event. Which is why this is less cumbersome to writing the whole delegate (blah blah) which also requires you to specify types of parameters.

Lambdas don't need to return anything and type inference is extremely powerful in context like this.

And BTW, you can always return Lambdas that make Lambdas in the functional programming sense. For example, here's a lambda that makes a lambda that handles a Button.Click event:

Func<int, int, EventHandler> makeHandler =
    (dx, dy) => (sender, e) => {
        var btn = (Button) sender;
        btn.Top += dy;
        btn.Left += dx;
    };

btnUp.Click += makeHandler(0, -1);
btnDown.Click += makeHandler(0, 1);
btnLeft.Click += makeHandler(-1, 0);
btnRight.Click += makeHandler(1, 0);

Note the chaining: (dx, dy) => (sender, e) =>

Now that's why I'm happy to have taken the functional programming class :-)

Other than the pointers in C, I think it's the other fundamental thing you should learn :-)


A couple I can think of:

[field: NonSerialized()]
public EventHandler event SomeEvent;

This prevents the event from being serialised. The 'field:' indicates that the attribute should be applied to the event's backing field.

Another little known feature is overriding the add/remove event handlers:

public event EventHandler SomeEvent
{
    add
    {
        // ...
    }

    remove
    {
        // ...
    }
}

The InternalsVisibleToAttribute specifies that types that are ordinarily visible only within the current assembly are visible to another assembly. Article on msdn


Events are really delegates under the hood and any delegate object can have multiple functions attached to it and detatched from it using the += and -= operators, respectively.

Events can also be controlled with the add/remove, similar to get/set except they're invoked when += and -= are used:

public event EventHandler SelectiveEvent(object sender, EventArgs args) 
  { add 
     { if (value.Target == null) throw new Exception("No static handlers!");
       _SelectiveEvent += value;
     }
    remove
     { _SelectiveEvent -= value;
     }
  } EventHandler _SelectiveEvent;

Another way of geting IEnumerable through yield without explicity creating an IEnumerable object

public IEnumerable<Request> SomeMethod(IEnumerable<Request> requests)
{
    foreach (Request request in requests)
       yield return DoSomthing(request);
}

The #region {string} and #endregion pair is very neat for grouping code (outlining).

#region Using statements
using System;
using System.IO;
using ....;
using ....;
#endregion

The code block can be compressed to a single describing line of text. Works inside functions aswell.


FIXED / Power of Pointers in C# - This topic is too big, but I will just outline simple things.

In C we had facility of loading structure like...

struct cType{
   char type[4];
   int  size;
   char name[50];
   char email[100];
}

cType myType;
fread(file, &mType, sizeof(mType));

We can use fixed keyword in "unsafe" method to read byte array aligned structure.

[Layout(LayoutKind.Sequential, Pack=1)]
public unsafe class CType{
    public fixed byte type[4];
    public int size;
    public fixed byte name[50];
    public fixed byte email[100];
}

Method 1 (Reading from regular stream in to byte buffer and mapping byte array to individual bytes of struct)

CType mType = new CType();
byte[] buffer = new byte[Marshal.SizeOf(CType)];
stream.Read(buffer,0,buffer.Length);
// you can map your buffer back to your struct...
fixed(CType* sp = &mType)
{
    byte* bsp = (byte*) sp;
    fixed(byte* bp = &buffer)
    {
         for(int i=0;i<buffer.Length;i++)
         {
             (*bsp) = (*bp);
             bsp++;bp++;
         }
    }
}

Method 2, you can map Win32 User32.dll's ReadFile to directly read bytes...

CType mType = new CType();
fixed(CType* p = &mType)
{
    User32.ReadFile(fileHandle, (byte*) p, Marshal.SizeOf(mType),0);
}

Mixins. Basically, if you want to add a feature to several classes, but cannot use one base class for all of them, get each class to implement an interface (with no members). Then, write an extension method for the interface, i.e.

public static DeepCopy(this IPrototype p) { ... }

Of course, some clarity is sacrificed. But it works!


If you want to exit your program without calling any finally blocks or finalizers use FailFast:

Environment.FailFast()

In reading the book on development of the .NET framework. A good piece of advice is not to use bool to turn stuff on or off, but rather use ENums.

With ENums you give yourself some expandability without having to rewrite any code to add a new feature to a function.


You can use generics to check (compile time) if a method argument implements two interfaces:

interface IPropA 
{
    string PropA { get; set; } 
}

interface IPropB 
{
    string PropB { get; set; }
}

class TestClass 
{
    void DoSomething<T>(T t) where T : IPropA, IPropB 
    {
        MessageBox.Show(t.PropA);
        MessageBox.Show(t.PropB);
    }
}

Same with an argument that is inherited from a base class and an interface.


Array initialization without specifying the array element type:

var pets = new[] { "Cat", "Dog", "Bird" };

From Rick Strahl:

You can chain the ?? operator so that you can do a bunch of null comparisons.

string result = value1 ?? value2 ?? value3 ?? String.Empty;

I didn't start to really appreciate the "using" blocks until recently. They make things so much more tidy :)


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);

@lomaxx I also learned the other day (the same time I learned your tip) is that you can now have disparate access levels on the same property:

public string Name { get; private set;}

That way only the class itself can set the Name property.

public MyClass(string name) { Name = name; }

Zero parameter Lambdas

()=>Console.ReadLine()

Not sure if this one got mentioned yet but the ThreadStatic attribute is a realy useful one. This makes a static field static just for the current thread.

[ThreadStatic]
private static int _ThreadStaticInteger;

You should not include an initializer because it only get executed once for the entire application, you're better off making the field nullable and checking if the value is null before you use it.

And one more thing for ASP.NET applications threads are reused so if you modify the value it could end up being used for another page request.

Still I have found this useful on several occasions. For example in creating a custom transaction class that:

using (DbTransaction tran = new DbTransaction())
{
    DoQuery("...");
    DoQuery("...");    
}

The DbTransaction constructor sets a ThreadStatic field to its self and resets it to null in the dispose method. DoQuery checks the static field and if != null uses the current transaction if not it defaults to something else. We avoid having to pass the transaction to each method plus it makes it easy to wrap other methods that were not originaly meant to be used with transaction inside a transaction ...

Just one use :)


RealProxy lets you create your own proxies for existing types.

This is super-advanced and I haven't seen anyone else use it -- which may mean that it's also really not that useful for most folks -- but it's one of those things that's good to know.

Basically, the .NET RealProxy class lets you create what is called a transparent proxy to another type. Transparent in this case means that it looks completely like the proxied target object to its client -- but it's really not: it's an instance of your class, which is derived from RealProxy.

This lets you apply powerful and comprehensive interception and "intermediation" services between the client and any methods or properties invoked on the real target object. Couple this power with the factory pattern (IoC etc), and you can hand back transparent proxies instead of real objects, allowing you to intercept all calls to the real objects and perform actions before and after each method invocation. In fact, I believe this is the very functionality .NET uses for remoting across app domain, process, and machine boundaries: .NET intercepts all access, sends serialized info to the remote object, receives the response, and returns it to your code.

Maybe an example will make it clear how this can be useful: I created a reference service stack for my last job as enterprise architect which specified the standard internal composition (the "stack") of any new WCF services across the division. The model mandated that the data access layer for (say) the Foo service implement IDAL<Foo>: create a Foo, read a Foo, update a Foo, delete a Foo. Service developers used supplied common code (from me) that would locate and load the required DAL for a service:

IDAL<T> GetDAL<T>(); // retrieve data access layer for entity T

Data access strategies in that company had often been, well, performance-challenged. As an architect, I couldn't watch over every service developer to make sure that he/she wrote a performant data access layer. But what I could do within the GetDAL factory pattern was create a transparent proxy to the requested DAL (once the common service model code located the DLL and loaded it), and use high-performance timing APIs to profile all calls to any method of the DAL. Ranking laggards then is just a matter of sorting DAL call timings by descending total time. The advantage to this over development profiling (e.g. in the IDE) is that it can be done in the production environment as well, to ensure SLAs.

Here is an example of test code I wrote for the "entity profiler," which was common code to create a profiling proxy for any type with a single line:

[Test, Category("ProfileEntity")]
public void MyTest()
{
    // this is the object that we want profiled.
    // we would normally pass this around and call
    // methods on this instance.
    DALToBeProfiled dal = new DALToBeProfiled();

    // To profile, instead we obtain our proxy
    // and pass it around instead.
    DALToBeProfiled dalProxy = (DALToBeProfiled)EntityProfiler.Instance(dal);

    // or...
    DALToBeProfiled dalProxy2 = EntityProfiler<DALToBeProfiled>.Instance(dal);

    // Now use proxy wherever we would have used the original...
    // All methods' timings are automatically recorded
    // with a high-resolution timer
    DoStuffToThisObject(dalProxy);

    // Output profiling results
    ProfileManager.Instance.ToConsole();
}

Again, this lets you intercept all methods and properties called by the client on the target object! In your RealProxy-derived class, you have to override Invoke:

[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[SecurityPermission(SecurityAction.LinkDemand, 
    Flags = SecurityPermissionFlag.Infrastructure)] // per FxCop
public override IMessage Invoke(IMessage msg)
{
    IMethodCallMessage msgMethodCall = msg as IMethodCallMessage;
    Debug.Assert(msgMethodCall != null); // should not be null - research Invoke if this trips. KWB 2009.05.28

    // The MethodCallMessageWrapper
    // provides read/write access to the method 
    // call arguments. 
    MethodCallMessageWrapper mc =
        new MethodCallMessageWrapper(msgMethodCall);

    // This is the reflected method base of the called method. 
    MethodInfo mi = (MethodInfo)mc.MethodBase;

    IMessage retval = null;

    // Pass the call to the method and get our return value
    string profileName = ProfileClassName + "." + mi.Name;

    using (ProfileManager.Start(profileName))
    {
        IMessage myReturnMessage =
           RemotingServices.ExecuteMessage(_target, msgMethodCall);

        retval = myReturnMessage;
    }

    return retval;
}

Isn't it fascinating what .NET can do? The only restriction is that the target type must be derived from MarshalByRefObject. I hope this is helpful to someone.


I didn't find anyone who is using string.Join to join strings using a separator. Everyone keeps writing the same ugly for-loop

var sb = new StringBuilder();
var count = list.Count();
for(int i = 0; i < count; i++)
{
  if (sb.Length > 0) sb.Append(seperator);
  sb.Append(list[i]);
}

return sb.ToString();

instead of

return string.Join(separator, list.ToArray());

When you need to (a)synchronously communicate between objects about occurance of an event there is special purpose interface called ISynchronizeInvoke.

Quoting MSDN article (link):

Objects that implement this interface can receive notification that an event has occurred, and they can respond to queries about the event. In this way, clients can ensure that one request has been processed before they submit a subsequent request that depends on completion of the first.

Here is a generic wrapper:

protected void OnEvent<T>(EventHandler<T> eventHandler, T args) where T : EventArgs
{
    if (eventHandler == null) return;

    foreach (EventHandler<T> singleEvent in eventHandler.GetInvocationList())
    {
        if (singleEvent.Target != null && singleEvent.Target is ISynchronizeInvoke)
        {
            var target = (ISynchronizeInvoke)singleEvent.Target;

            if (target.InvokeRequired) {
                target.BeginInvoke(singleEvent, new object[] { this, args });
                continue;
            }
        }
        singleEvent(this, args);
    }
}

and here is an example usage:

public event EventHandler<ProgressEventArgs> ProgressChanged;

private void OnProgressChanged(int processed, int total)
{
    OnEvent(ProgressChanged, new ProgressEventArgs(processed, total));
}

Reflection Emit and Expression trees come to mind...

Don't miss Jeffrey Richter's CLR via C# and Jon Skeet's alt text

See here for some resources:

http://www.codeproject.com/KB/trace/releasemodebreakpoint.aspx

http://www.codeproject.com/KB/dotnet/Creating_Dynamic_Types.aspx

http://www.codeproject.com/KB/cs/lambdaexpressions.aspx


Nested classes can access private members of a outer class.

public class Outer
{
    private int Value { get; set; }

    public class Inner
    {
        protected void ModifyOuterMember(Outer outer, int value)
        {
            outer.Value = value;
        }
    }
}

And now together with the above feature you can also inherit from nested classes as if they were top level classes as shown below.

public class Cheater : Outer.Inner
{
    protected void MakeValue5(Outer outer)
    {
        ModifyOuterMember(outer, 5);
    }
}

These features allow for some interesting possibilities as far as providing access to particular members via somewhat hidden classes.


Four switch oddities by Eric Lippert


fixed statement

This statement prevents the garbage collector from relocating a movable variable. Fixed can also be used to create fixed size buffers.

The fixed statement sets a pointer to a managed variable and "pins" that variable during the execution of statement.

stackalloc

The stackalloc allocates a block of memory on the stack.


@lainMH,

Nullable booleans are useful when retrieving values from a database that are nullable and when putting values back in. Sometimes you want to know the field has not been set.


Collection Initializer inside Object Initializer:

MailMessage mail = new MailMessage {
   To = { new MailAddress("[email protected]"), new MailAddress("[email protected]") },
   Subject = "Password Recovery"
};

You can initialize a whole tree in a single expression.


There's also the ThreadStaticAttribute to make a static field unique per thread, so you can have strongly typed thread-local storage.

Even if extension methods aren't that secret (LINQ is based on them), it may not be so obvious as to how useful and more readable they can be for utility helper methods:

//for adding multiple elements to a collection that doesn't have AddRange
//e.g., collection.Add(item1, item2, itemN);
static void Add<T>(this ICollection<T> coll, params T[] items)
 { foreach (var item in items) coll.Add(item);
 }

//like string.Format() but with custom string representation of arguments
//e.g., "{0} {1} {2}".Format<Custom>(c=>c.Name,"string",new object(),new Custom())
//      result: "string {System.Object} Custom1Name"
static string Format<T>(this string format, Func<T,object> select, params object[] args)
 { for(int i=0; i < args.Length; ++i)
    { var x = args[i] as T;
      if (x != null) args[i] = select(x);
    }
   return string.Format(format, args);
 }

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


IEnumerable's SelectMany, which flattens a list of lists into a single list. Let's say I have a list of Orders, and each Order has a list of LineItems on that order.

I want to know the total number of LineItems sold...

int totalItems = Orders.Select(o => o.LineItems).SelectMany(i => i).Sum();

Extension methods can be called on null; this will not cause a NullReferenceException to be thrown.

Example application: you can define an alternative for ToString() called ToStringOrEmpty() which will return the empty string when called on null.


If 3rd-party extensions are allowed, then C5 and Microsoft CCR (see this blog post for a quick introduction) are a must-know.

C5 complements .Net's somewhat lacking collections library (not Set???), and CCR makes concurrent programming easier (I hear it's due to be merged with Parallel Extensions).


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" } };

Exception Filters. So "hidden" you can't even use them (at least from C#) without a post-compilation patch ;)


How about the FlagsAttribute on an enumeration? It allows you to perform bitwise operations... took me forever to find out how to do bitwise operations in .NET nicely.


Preprocessor Directives can be nifty if you want different behavior between Debug and Release modes.

http://msdn.microsoft.com/en-us/library/ed8yd1ha.aspx


I picked this one up when using ReSharper:

Implicit Method Group Conversion

//If given this:
var myStrings = new List<string>(){"abc","def","xyz"};
//Then this:
myStrings.ForEach(s => Console.WriteLine(s));
//Is equivalent to this:
myStrings.ForEach(Console.WriteLine);

See "Implicit Method Group Conversion in C#" for more.


You can "use" multiple objects in one using statement.

using (Font f1= new Font("Arial", 10.0f), f2 = new Font("Arial", 10.0f))
{
    // Use f1 and f2.
}

Note that there is already an answer stating that you can do this:

using (Font f1= new Font("Arial", 10.0f))
using (Font f2 = new Font("Arial", 10.0f))
{    }

Which is different from mine.


In no particular order:

Lists<>
Mutex

The new property definitions shortcut in Framework 3.5.


PreviousPage property:

"The System.Web.UI.Page representing the page that transferred control to the current page."

It is very useful.


Generics and the Curiously-Recurring Template Pattern really help with some static method/property declarations.

Suppose you are building a class hierarchy:

class Base
{
}

class Foo: Base
{
}

class Bar: Base
{
}

Now, you want to declare static methods on your types that should take parameters (or return values) of the same type or static properties of the same type. For example, you want:

class Base
{
    public static Base Get()
    {
        // Return a suitable Base.
    }
}

class Foo: Base
{
    public static Foo Get()
    {
        // Return a suitable Foo.
    }
}

class Bar: Base
{
    public static Bar Get()
    {
        // Return a suitable Bar.
    }
}

If these static methods basically all do the same thing, then you have lots of duplicated code on your hands. One solution would be to drop type safety on the return values and to always return type Base. However, if you want type safety, then the solution is to declare the Base as:

class Base<T> where T: Base<T>
{
    public static T Get<T>()
    {
        // Return a suitable T.
    }
}

and you Foo and Bar as:

class Foo: Base<Foo>
{
}

class Bar: Base<Bar>
{
}

This way, they will automatically get their copies of the static methods.

This also works wonders to encapsulate the Singleton pattern in a base class (I know the code below is not thread-safe, it just to demonstrate a point):

public class Singleton<T> where T: Singleton<T>, new()
{
  public static T Instance { get; private set; }

  static Singleton<T>()
  {
    Instance = new T();
  }
}

I realize that this forces you to have a public parameterless constructor on your singleton subclass but there is no way to avoid that at compile time without a where T: protected new() construct; however one can use reflection to invoke the protected/private parameterless constructor of the sub-class at runtime to achieve that.


Atrribute Targets

Everyone has seen one. Basically, when you see this:

[assembly: ComVisible(false)]

The "assembly:" portion of that attribute is the target. In this case, the attribute is applied to the assembly, but there are others:

[return: SomeAttr]
int Method3() { return 0; } 

In this sample the attribute is applied to the return value.


I find this technique interesting while working with linqxml:

public bool GetFooSetting(XElement ndef){
   return (bool?)ndef.Element("MyBoolSettingValue") ?? true;
}

as opposed to:

public bool GetFooSetting(XElement ndef){
   return ndef.Element("MyBoolSettingValue") != null ? bool.Parse(ndef.Element("MyBoolSettingValue") ) : true;
}

Honestly the experts by the very definition should know this stuff. But to answer your question: Built-In Types Table (C# Reference)

The compiler flagging for numbers are widely known for these:

Decimal = M
Float = F
Double = D

// for example
double d = 30D;

However these are more obscure:

Long = L
Unsigned Long = UL
Unsigned Int = U

One feature that I only learned about here on Stack Overflow was the ability to set an attribute on the return parameter.

[AttributeUsage( AttributeTargets.ReturnValue )]
public class CuriosityAttribute:Attribute
{
}

public class Bar
{
    [return: Curiosity]
    public Bar ReturnANewBar()
    {
        return new Bar();
    }
}

This was truly a hidden feature for me :-)


This one is not "hidden" so much as it is misnamed.

A lot of attention is paid to the algorithms "map", "reduce", and "filter". What most people don't realize is that .NET 3.5 added all three of these algorithms, but it gave them very SQL-ish names, based on the fact that they're part of LINQ.

"map" => Select
Transforms data from one form into another

"reduce" => Aggregate
Aggregates values into a single result

"filter" => Where
Filters data based on a criteria

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.


The data type can be defined for an enumeration:

enum EnumName : [byte, char, int16, int32, int64, uint16, uint32, uint64]
{
    A = 1,
    B = 2
}

Instead of using int.TryParse() or Convert.ToInt32(), I like having a static integer parsing function that returns null when it can't parse. Then I can use ?? and the ternary operator together to more clearly ensure my declaration and initialization are all done on one line in a easy-to-understand way.

public static class Parser {
    public static int? ParseInt(string s) {
        int result;
        bool parsed = int.TryParse(s, out result);
        if (parsed) return result;
        else return null;
    }
    // ...
}

This is also good to avoid duplicating the left side of an assignment, but even better to avoid duplicating long calls on the right side of an assignment, such as a database calls in the following example. Instead of ugly if-then trees (which I run into often):

int x = 0;
YourDatabaseResultSet data = new YourDatabaseResultSet();
if (cond1)
    if (int.TryParse(x_input, x)){
        data = YourDatabaseAccessMethod("my_proc_name", 2, x);
    }
    else{
        x = -1;
        // do something to report "Can't Parse"    
    }
}
else {
    x = y;
    data = YourDatabaseAccessMethod("my_proc_name", 
       new SqlParameter("@param1", 2),
       new SqlParameter("@param2", x));
}

You can do:

int x = cond1 ? (Parser.ParseInt(x_input) ?? -1) : y;
if (x >= 0)  data = YourDatabaseAccessMethod("my_proc_name", 
    new SqlParameter("@param1", 2),
    new SqlParameter("@param2", x));

Much cleaner and easier to understand


I love abusing the fact that static templated classes don't share their static members.

Here's a threadsafe (at creation time) and cheap substitute to any Dictionary<Type,...> when the Type instance is known at compile-time.

public static class MyCachedData<T>{
    static readonly CachedData Value;
    static MyCachedData(){
       Value=// Heavy computation, such as baking IL code or doing lots of reflection on a type
    }
}

Cheers, Florian


I like

#if DEBUG
           //Code run in debugging mode

#else
           //Code run in release mode

#endif

Open generics are another handy feature especially when using Inversion of Control:

container.RegisterType(typeof(IRepository<>), typeof(NHibernateRepository<>));

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.


The #if DEBUG pre-processor directive. It is Useful for testing and debugging (though I usually prefer to go the unit testing route).

string customerName = null;
#if DEBUG
  customerName = "Bob"
#endif

It will only execute code block if Visual Studio is set to compile in 'Debug' mode. Otherwise the code block will be ignored by the compiler (and grayed out in Visual Studio).


Several people have mentioned using blocks, but I think they are much more useful than people have realised. Think of them as the poor man's AOP tool. I have a host of simple objects that capture state in the constructor and then restore it in the Dispose() method. That allows me to wrap a piece of functionality in a using block and be sure that the state is restored at the end. For example:

using(new CursorState(this, BusyCursor));
{
    // Do stuff
}

CursorState captures the current cursor being used by form, then sets the form to use the cursor supplied. At the end it restores the original cursor. I do loads of things like this, for example capturing the selections and current row on a grid before refreshing and so on.


I didn't discover - for almost a year - that Strongly Typed DataRows contain an Is[ColumnName]Null() method.

For example:

Units.UnitsDataTable dataTable = new Units.UnitsDataTable();

foreach (Units.UnitsRow row in dataTable.Rows)
{
    if (row.IsPrimaryKeyNull())
        //....

    if (row.IsForeignKeyNull())
        //....
}

Everything else, plus

1) implicit generics (why only on methods and not on classes?)

void GenericMethod<T>( T input ) { ... }

//Infer type, so
GenericMethod<int>(23); //You don't need the <>.
GenericMethod(23);      //Is enough.

2) simple lambdas with one parameter:

x => x.ToString() //simplify so many calls

3) anonymous types and initialisers:

//Duck-typed: works with any .Add method.
var colours = new Dictionary<string, string> {
    { "red", "#ff0000" },
    { "green", "#00ff00" },
    { "blue", "#0000ff" }
};

int[] arrayOfInt = { 1, 2, 3, 4, 5 };

Another one:

4) Auto properties can have different scopes:

public int MyId { get; private set; }

Thanks @pzycoman for reminding me:

5) Namespace aliases (not that you're likely to need this particular distinction):

using web = System.Web.UI.WebControls;
using win = System.Windows.Forms;

web::Control aWebControl = new web::Control();
win::Control aFormControl = new win::Control();

From CLR via C#:

When normalizing strings, it is highly recommended that you use ToUpperInvariant instead of ToLowerInvariant because Microsoft has optimized the code for performing uppercase comparisons.

I remember one time my coworker always changed strings to uppercase before comparing. I've always wondered why he does that because I feel it's more "natural" to convert to lowercase first. After reading the book now I know why.


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:


There are some really hidden keywords and features in C# related to the TypedReference undocumented class. The following keywords are undocumented:

  • __makeref
  • __reftype
  • __refvalue
  • __arglist

Examples of use:

// Create a typed reference
int i = 1;
TypedReference tr1 = __makeref(i);
// Get the type of a typed reference
Type t = __reftype(tr1);
// Get the value of a typed referece
int j = __refvalue(tr1, int); 
// Create a method that accepts and arbitrary number of typed references
void SomeMethod(__arglist) { ...
// Call the method
int x = 1;
string y = "Foo";
Object o = new Object();
SomeMethod(__arglist(x,y,o));
// And finally iterate over method parameters
void SomeMethod(__arglist) {
    ArgIterator ai = new ArgIterator(__arglist);
while(ai.GetRemainingCount() >0)
{
      TypedReference tr = ai.GetNextArg();
      Console.WriteLine(TypedReference.ToObject(tr));
}}

If you have the search textbox in your Visual Studio toolbar, you can type ">of Program.cs" to open the file Program.cs


Other underused operators are checked and unchecked:

short x = 32767;   // 32767 is the max value for short
short y = 32767;
int z1 =  checked((short)(x + y));   //will throw an OverflowException
int z2 =  unchecked((short)(x + y)); // will return -2
int z3 =  (short)(x + y);            // will return -2

I like the keyword continue.

If you hit a condition in a loop and don't want to do anything but advance the loop just stick in "continue;".

E.g.:

foreach(object o in ACollection)
{
  if(NotInterested)
     continue;
}

FlagsAttribute, a small but nice feature when using enum to make a bitmasks:

[Flags]
public enum ConfigOptions
{
    None    = 0,
    A       = 1 << 0,
    B       = 1 << 1,
    Both    = A | B
}

Console.WriteLine( ConfigOptions.A.ToString() );
Console.WriteLine( ConfigOptions.Both.ToString() );
// Will print:
// A
// A, B

What about using this:

#if DEBUG
            Console.Write("Debugging");
#else
            Console.Write("Final");
#endif

When you have your solution compiled with DEBUG defined it will output "Debugging".

If your compile is set to Release it will write "Final".


Maybe not an advanced technique, but one I see all the time that drives me crazy:

if (x == 1)
{
   x = 2;
}
else
{
   x = 3;
}

can be condensed to:

x = (x==1) ? 2 : 3;

Most of the P/Invoke stuff is a bit strange.

Example of attributes:

[DllImport ("gdi32.dll")] 
[return : MarshalAs(UnmanagedType.I4)]
[StructLayout(LayoutKind.Sequential)]

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

(_, b, __) => b.DoStuff();  // only interested in b here

ConditionalAttribute

Allows you to tell the compiler to omit the call to the method marked with the attribute under certain conditions (#define).

The fact that the method call is omitted also means that its parameters are not evaluated. This is very handy and it's what allows you to call expensive validation functions in Debug.Assert() and not worry about them slowing down your release build.


Pointers in C#.

They can be used to do in-place string manipulation. This is an unsafe feature so the unsafe keyword is used to mark the region of unsafe code. Also note how the fixed keyword is used to indicate that the memory pointed to is pinned and cannot be moved by the GC. This is essential a pointers point to memory addresses and the GC can move the memory to different address otherwise resulting in an invalid pointer.

    string str = "some string";
    Console.WriteLine(str);
    unsafe
    {
        fixed(char *s = str)
        {
            char *c = s;
            while(*c != '\0')
            {
                *c = Char.ToUpper(*c++);                    
            }
        }
    }
    Console.WriteLine(str);

I wouldn't ever do it but just for the sake of this question to demonstrate this feature.