Willy's Reflections

| Willy-Peter Schaub | Visual Studio ALM Rangers | In search of IT simplicity, quality and tranquility |

VSTS 2010 – Some cool new features in C# 4: Default & Named Parameters and Dynamic Types (part 1 of many)

VSTS 2010 – Some cool new features in C# 4: Default & Named Parameters and Dynamic Types (part 1 of many)

  • Comments 2

I have been looking at some of the innovations coming from C# 4, whereby the following have caught my eye. These are “old news” to C++ developers for example, but definitely “new news” for C# 2 and 3 developers q;-)

Default and Named Parameters

Finally the default parameters are back, allowing us to literally cleanup a lot of code noise we had to do to work around the lack thereof, i.e. by using operation overloads.

   1: protected void SampleMethod (bool initaliseEngine = true)
   2: {
   3:   // note the = true in the method signature --> default parameter
   4:   ...
   5: }
   6:  
   7: protected void SomeMethod()
   8: {
   9:   ...
  10:   // note the argument name : value --> named parameter
  11:   SampleMethod (initialiseEngine: true); 
  12: }

Dynamic Types

One of the features that made me frown, still has me worried, but which may prove valuable is the dynamic type, which instructs the compiler to resolve the type only at runtime. This means that we can p[potentially write code that calls methods on the type, which may not actually exist, resulting in runtime debugging journeys.

   1: ...
   2: dynamic dynamicType = CreateTypeFromFactory(...);
   3:         dynamicType.ToString();    // we assume it has a ToString() method
   4: int     valueTest   = dynamicType; //convert from type dynamic to int

Looking forward to finding more C# 4 nuggets q;-) … see you soon.

Page 1 of 1 (2 items)
Leave a Comment
  • Please add 6 and 2 and type the answer here:
  • Post