10 features in C# that you really should learn (and use!)

If you start exploring C# or decide to expand your knowledge, you should learn these useful language features, which will help you to simplify the code, avoid errors and save a lot of time.

1) async / await

Use the async / await-pattern to allow unblocking of the UI / current thread when execution blocking operations. The async / await-pattern works by letting the code continue executing even if something is blocking the execution (like a web request).

Read more about the async / await-pattern here: https://msdn.microsoft.com/en-us/library/hh191443.aspx

2) Object / array / collection initializers

Create instances of classes, arrays and collections easily by using the object, array and collection initializers:

//Just some demo class
public class Employee {
    public string Name {get; set;}
    public DateTime StartDate {get; set;}

//Create an employlee by using the initializer
Employee emp = new Employee {Name="John Smith", StartDate=DateTime.Now()};

The above example can be really useful in unit testing but should be avoided in other contexts as instances of classes should be created using a constructor.

Read more about initializers here: https://msdn.microsoft.com/en-us/library/bb384062.aspx

3) Lambdas, predicates, delegates and closures

These features are practically a necessity in many cases (e.g. when using Linq), make sure to actually learn when and how to use them.

Read more about Lambdas, predicates, delegates and closure here: http://www.codeaddiction.net/articles/13/lambda-expressions-delegates-predicates-and-closures-in-c

4) ?? (Null coalescing operator)

The ??-operator returns the left side as long as it’s not null, in that case the right side will be returned:

//May be null
var someValue = service.GetValue();
var defaultValue = 23

//result will be 23 if someValue is null
var result = someValue ?? defaultValue;

The ??-operator can be chained:

string anybody = parm1 ?? localDefault ?? globalDefault;

And it can be used to convert nullable types to non nullable:

var totalPurchased = PurchaseQuantities.Sum(kvp => kvp.Value ?? 0);

Read more about the ??-operator here: https://msdn.microsoft.com/en-us/library/ms173224.aspx

5) $”{x}” (String Interpolation) – C# 6

A new feature of C# 6 that lets you assemble strings in an efficient and elegant way:

//Old way
var someString = String.Format("Some data: {0}, some more data: {1}", someVariable, someOtherVariable);

var someString = $"Some data: {someVariable}, some more data: {someOtherVariable}";

You can put C# expressions in between the braces, which makes this very powerful.

6) ?. (Null-conditional operator) – C# 6

The null-conditional operator works like this:

//Null if customer or customer.profile or customer.profile.age is null
var currentAge = customer?.profile?.age;

No more NullReferenceExceptions!

Read more about the ?.-operator here: https://msdn.microsoft.com/en-us/library/dn986595.aspx

7) nameof Expression – C# 6

So the new nameof-expression might not seem important, but it really has it value. When using automatic re-factoring tools (like ReSharper) you sometime need to refer to a method argument by it’s name:

public void PrintUserName(User currentUser)
    //The refactoring tool might miss the textual reference to current user 
    below if we're renaming it
    if(currentUser == null)
        _logger.Error("Argument currentUser is not provided");


This is how you should use it…

public void PrintUserName(User currentUser)
    //The refactoring tool will not miss this...
    if(currentUser == null)
        _logger.Error($"Argument {nameof(currentUser)} is not provided");


Read more about the nameof-expression here: https://msdn.microsoft.com/en-us/library/dn986596.aspx

8) Property Initializers – C# 6

Property initializers lets you declare an initial value for a property:

public class User
    public Guid Id { get; } = Guid.NewGuid();
    // ...

A benefit of using property initializers is that you can not declare a set:er, thus making the property immutable. Property initializers works great together with C# 6 primary constructor syntax.

9) as and is-operators

The is-operator is used to control if an instance is of a specific type, e.g. if you want to see if a cast is possible:

if (Person is Adult)
    //do stuff

Use the as-operator to try to cast an instance to a class. It will return null if cast was not possible:

SomeType y = x as SomeType;
if (y != null)
    //do stuff

10) yield-keyword

The yield-keyword lets you feed an an IEnumerable-interface with items. The following example will return each powers of 2 up to the exponent of 8 (e.g. 2, 4, 8, 16, 32, 64, 128 ,256):

public static IEnumerable Power(int number, int exponent)
    int result = 1;
    for (int i = 0; i < exponent; i++)
      result = result * number;
      yield return result;

yield return can be very powerful if it’s used in the correct way. It enables you to lazily generate a sequence of objects, ie. the system does not have to enumerate the whole collection – it can be done on demand.

Source CodeAddiction.net

6 thoughts on “10 features in C# that you really should learn (and use!)

  1. Pingback: 10 features in C# that you really should learn (and use!) - How to Code .NET

  2. This is a good article. So many new features get added to C# that I read about them, think to myself, that is great, but then I go back to my day-to-day programming and never actually use it. Of course, this means that a week later I have completely forgot about them! πŸ™‚


  3. Would it be good to mention that, if using the `is` casting, when it returns true you’d have to cast it again to use it? Could lead to performance problems in bigger projects. πŸ™‚


  4. I’m guilty of a few of these! It’s interesting to read, but, any reason why as I want to learn!

    e.g. number 2 – I use this a heck of a lot – I don’t mind using constructors, but, I don’t get the benefit?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s