Tutorial :Hidden Features of C#? [closed]


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:




Language Features

Visual Studio Features


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



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.


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


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.



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


@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


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.


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


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


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


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.


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

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


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.



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.


//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:



Method groups aren't well known.


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


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;  


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.


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.


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


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


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.


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  }  


The data type can be defined for an enumeration:

enum EnumName : [byte, char, int16, int32, int64, uint16, uint32, uint64]  {      A = 1,      B = 2  }  


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


Open generics are another handy feature especially when using Inversion of Control:

container.RegisterType(typeof(IRepository<>), typeof(NHibernateRepository<>));  


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.


In no particular order:

Lists<>  Mutex  

The new property definitions shortcut in Framework 3.5.


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


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


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:


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »