Monday, February 25, 2013

6 Simple New(er) C#/.Net features you may have missed

So you're on an interview for a .NET job and you're feeling pretty good about yourself.  You've been using Visual Studio 2012 and .NET 4.5 for the last few months and your resume indicates the same; and then this question :

What are your favorite new features in C# 5.0 and .NET 4.5?

Uhh.. Well.  I....

It's actually a pretty difficult question this time around because it's not a major release and I would say that 3.0/3.5 was the last time I observed a radical change in the way we we write C#.

But could you even answer the question for .NET 4?    In this post I'm going to try to remind you of some of the features of C# 5.0/4.0 and .NET 4/4.5  that are both easy to remember and use.


BigInteger 


I thought we'd start simple.  In the Framework Class Library, there is a new DLL (System.Numerics) with  only two public types in it; one of them is the BigInteger struct.  BigInteger allows for arbitrarily long integers and could find use in scientific programming.

Tuple 


One of my favorite features in .NET 4 is the addition of the Tuple.  Tuples allow you to easily capture related values without having to go through the trouble of creating a new class.  It's a much more flexible concept than the KeyValuePair class because they can hold up to 8 values.

Tuple is a borrowed concept from F# that's been wedged into C# using the power of generics (and the copying and pasting of a class about 8 times).

Here's an example of the usage


   1:  public void Tuple()
   2:          {
   3:              var tup = new System.Tuple<int, string, DateTime>(1, "Brian", DateTime.Now);
   4:              Debug.Write(tup.Item1 + tup.Item2 + tup.Item3);
   5:          }


Here's the class I used above (The version that holds 3 generic values)


   1:  namespace System
   2:  {
   3:      [Serializable]
   4:      public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
   5:      {
   6:          public Tuple(T1 item1, T2 item2, T3 item3);
   7:   
   8:          public T1 Item1 { get; }
   9:       
  10:          public T2 Item2 { get; }
  11:       
  12:          public T3 Item3 { get; }
  13:   
  14:          public override bool Equals(object obj);
  15:          
  16:          public override int GetHashCode();
  17:        
  18:          public override string ToString();
  19:      }
  20:  }

Interesting to note that, yes there are 8 different versions of the class to support Tuples that hold up to 8 values.

Caller Information Attributes


Calling method arguments are a very useful feature implemented in the C# 5.0 compiler.  Now you can get information about how your method was called.  This is a huge improvement on having to look into the stack trace in order to achieve diagnostic level logging.  Here's an example of how it would work in a method that takes a string parameter.














Named and optional Arguments

Named and optional arguments are one of my favorite features because they allow API designers to have a LOT of calling options (as long as there are defaults) but not make your code verbose; I find any API taking advantage of this to be pure bliss.

Named Parameters allow you to specify  your parameters in any order and omit any parameters with defaults as long as everything without a default value is specified.

So for example, both of the following method calls are valid


   1:          public void NamedParameters()
   2:          {
   3:              OutPut(message: "Test");
   4:              OutPut(message: "Test", newLine:false);
   5:          }
   6:   
   7:          public void OutPut(bool newLine = true, string message = "TestMessage", bool AddAmperSand = true)
   8:          {
   9:              Debug.Write(message);
  10:              if (AddAmperSand) Debug.Write("&");
  11:              if (newLine) Debug.Write(Environment.NewLine);
  12:          }


Named parameters have another benefit; if you're working with a lot of code that has verbose calls that look like SendMessage(true, true,"messageData", false, 5)  and are completely unreadable because of the number of parameters.

you can refactor them into something like SendMessage(Repeat:true, Tolerance:true, Data:"MessageData", Alerts:false, RepeatSignal:5)

Of course this isn't a hard and fast rule, but more of a preference (I probably still lean toward the original.  There could be even more arguments though.).

ExpandoObject


An object you can dynamically add members to.  Lack of practical examples aside, there is a lot of possibilities because you can nest ExpandoObjects to create structured data (think XML-like/HTML-like).  You can think of ExpandoObjects as a Dictionary on steroids.  ExpandoObject is apart of the much bigger support for the Dynamic type introduced in C# 4.

   1:  public void ExpandoObject()
   2:          {
   3:              dynamic sampleObject = new System.Dynamic.ExpandoObject();
   4:              sampleObject.Test = "TestDynamic";
   5:              sampleObject.InvokeExpandoObject = new Action(() => Console.Write(sampleObject.Test));
   6:              sampleObject.InvokeExpandoObject.Invoke();
   7:          }

Parallel.ForEach


This concept is a small part of the much bigger task parallel library introduced in .NET 4.  The task parallel library is a collection of classes designed to make threading and parallel code easier to write.

If you have a list that needs to be processed, and you don't care about the order in which your items are processed, parallelizing your loop is likely a good idea. This is a really powerful concept because you aren't actually working with tasks at all and get the benefit of having your work parallelized.



Here's a simple example where we output a list in parallel.  You'll see the names don't come out in their original order.  Also, it should be noted that the overhead of the TPL is almost definitely not worth it in this scenario and is actually probably slower than a regular loop.

Conclusion / Download

You'll notice I left out Async/Await, Dynamic and Covariant/Contravariant generics and probably a bunch of other features.  The reason was to show you some of the SIMPLEST new features that will make your life easier.

It should be noted that the only feature I went over that's actually new in C# 5/ .NET 4.5 is calling method information--everything else is new as of .NET 4.

You can get the examples from this post here on bitBucket.  The total of all the examples is 70 lines!  Hopefully you've taken something away from this post.

4 comments:

  1. Good read, I've wanted something like the Tuple a long time. And the ExpandoObject was totally new to me.

    Thanks for posting :)

    /Jakob
    --
    http://www.xnafan.net

    ReplyDelete
  2. IStructuralEquatable can be used for Arrays also

    Prathap Kumar
    .Net Training

    ReplyDelete
  3. Very well written. Nice work. Thanks for sharing this.
    I am working in C#4.0 and .Net 4.0 for more than 1 year but reading this I think I am newbie in C# 4.0.
    Dot Net World

    ReplyDelete
  4. Tuples are bad. How is anyone reading your code supposed to know what "Item7" refers to?

    ReplyDelete