Since C# 4.0 was introduced by Anders at PDC 2008 there has been a lot of buzz about the features that have been added to the language and why. Many people have questions about why something like dynamic static types needed to be added and what was the thinking behind such decisions. I have wondered along with everyone else about many of these questions. Thankfully channel9 has managed to get an interview with Anders and asked him to clarify some of the reasoning behind the decisions they hade with the language. Video is below:
C# 4.0 - Questions and reasons behind the answers
.NET, Programming
Anders, C#, C# 4.0, channel9, PDC, PDC 2008, Programming
PDC 08 Day 1 did not disappoint. Here are some of the highlights from my day:
Keynote
They keynote was a pretty good introduction to Microsoft’s ideas about cloud computing and how they are going to bring it to the world. I was more interested in the “cloud” after leaving the keynote than I was when I walked in so I guess that’s a good thing. I can definitely see the benefit to putting and running a lot of stuff out in the cloud. I was pretty disappointed that there was no funny/quirky video (ala Bill’s last day) during the keynote.
CRM
My fist session was the MS CRM which was fairly interesting. The CRM 4 stuff was pretty basic where they highlighted CRM’s offline ability and the seamless way the UI can be integrated right into outlook. The really good stuff was when they showed the CRM 5 stuff. They have done some great stuff in the designer allowing admins to really do a lot more with customizing the forms in CRM and making them more useful. Things like related lookup fields which support the ability to cascade in the UI was a very cool feature. Other new features are filtering lists, native charts with drill-down, inline sub-grids, support for headers and footers in the forms. One other nice change was no more pop-up windows when you select records. Instead they change the main window to show the record and then the navigation around the frame changes and the left nav “slides” off screen hidden from view but still accessible when you mouse into the left side of the page.
C# Futures
By far the coolest session of the day was Ander’s C# futures talk (here is the video from this talk). Anders showed some of the really cool features coming in C# 4 as well as a few small peaks into 5! The changes in C# 4.0 centered around 4 topics:
- Dynamic typed objects (this is the main feature of 4.0) - Basically this introduces a new static type in C# called dynamic… yes the irony of this new type’s name wasn’t missed! LOL By using dynamic types you can allow the runtime to figure out the type of the object instead of the compiler. This allows you to write C# much in the same way you write JavaScript. In fact it’s so similar to the way you write JavaScript at one point Anders took some JS and pasted it into C# and changed “var” to “dynamic” and “function” to void and it compile and ran! Very Slick.
- Optional and named parameters - this is a great feature that will greatly reduce the number of signatures you need to write for some of your API’s. Basically it allows C# to act a bit like VB in the sense that you can have your method parameters be optional and assign them default values to be used if they are not passed in. Additionally the callers of methods can specify which parameter they are passing in by naming it in the call. This is done with a semicolon used in the method call - i.e. object.Method(message: “this is the message”);
- Improved COM interop - Microsoft leveraged the features from the new dynamic type and optional parameters to greatly simplify the calling of COM object from C# code. This essentially lets you call COM objects just like you would if you weren’t doing interop instead of having to pass in a bunch of placeholder objects for missing values.
- Co and Contra variance - Basically this features allows safe operations to be performed object that are more derived than their interface or delegate. So for instance you could pass a List<string> into a method that was taking IEnumberable<object> as an argument.
Beyond the 4.0 features Anders chatted a little bit about what they are tinkering with for C# 5.0. One of the biggest things they are doing is rewriting the C# compiler in managed code. Once the compiler is written in managed code the plan is to open up the compiler so that people can tinker around with it. Anders then proceeded to show a jaw dropping demo where he showed an application that could compile an app as you typed it into the command line and then show you the effects of the new compiled line of code immediately as you typed it. It was very impressive and the jam packed room was filled with open mouths and clapping hands.
After the sessions we headed over to the expo and stocked up on some conference swag. One of the most interesting things in the expo was Verne Troyer (aka mini-me) signing autographs at the devExpress booth.

All in all a great day @ PDC 2008!
.NET, Programming
C#, CRM, development, dynamic language, mini me, PDC, PDC 2008
At work we use a fair amount of enumerators in our code to define the values for lookup tables in the database. This a great way to implement these values because it avoids magic numbers and is easier to read and to maintain. But as much as I like working with enumerators, I’ve always struggled with the fact that I couldn’t bind them to list controls in the UI. Essentially there are 2 options you have to accomplish this:
1) Hard code the enumerated values into the list control - this is obviously a bad idea.
2) Just get the values from the DB since they are synchronized anyway - This idea actually works pretty well especially if you have a good caching mechanism in place
Even though #2 isn’t a terrible solution, it still bothered me to have to go to the DB to get values I already have defined in code. So I took a little time yesterday and wrote a method to populate a list control with the values of an enumerated type. Here is the code, note the last parameter will break apart your enumerator for better display - eg. ThisIsAnEnum will become This Is An Enum in the list control:
///
/// Populates a list based on the values of an enumerator
///
/// Web control to populate
/// An enumeration type
/// If true will break enum value with spaces on case change
public static void PopListFromEnum(ListControl list, System.Type enumType, bool spaceOnCase)
{
list.Items.Clear();
Array vals = Enum.GetValues( enumType);
for(int i = 0; i < vals.Length; i++)
{
string val = vals.GetValue(i).ToString();
string text = val;
if (spaceOnCase)
{
char[] cars = text.ToCharArray( 1, text.Length - 1 );
int offset = 1; // count the fact we are startng at position 1 to start with
for(int x = 0; x < cars.Length; x++)
{
if (Char.IsUpper( cars[x] ))
{
text = text.Insert( x + offset, " " );
offset += 1;
}
}
}
list.Items.Add( new ListItem( text, val ) );
}
}
Once you have the list populated to assign the selected value back out you can do something like this:
object.SomeEnum = (SomeEnum)Enum.Parse(typeof(SomeEnum), ListControl.SelectedValue);
.NET, Programming
Bind, C#, Enumerator
I was sifting through some code a co-worker of mine wrote this morning and noticed that they were handling the conversion of request params differently than I had in the past and so of course I was interested in knowing which approach was right (read: make sure all my previous code isn’t going to blow up). The specific issue here is in converting values in the Request.Params collection that are expected to be integers. In the past I have always handled this in the following manner:
int val = Convert.ToInt32(Request.Params["val"]);
Seemed simple enough with no apparent problems right? Well my co-workers code looked like this:
int val;
val = Request["val"] == null ? 0 : Int32.Parse( Request["val"] );
So my interest was peaked; what are the differences and the pros and cons between Parse vs. Convert? Which one is better? Does it even matter? In short - it really doesn’t matter which one you choose for the most part. However, there is an interesting difference between the two, and that is in how they handle null values. Convert will do all it can in it’s power to change what you passed in to the thing you ultimately asked for, so it will check for a null and upon finding one will simply return 0. Int32.Parse on the other hand is a little more sensitive in that it expects a valid integer value from the caller and will throw and exception when you pass in null. This all seems harmless until you add a little context.
If we look again at the second example we now realize that this could be done a lot more efficiently (in terms of simplicity) by using Convert instead of Parse because we can rely on Convert to do the null check for us. The end result would give us code that looks just like the first example.
However, if we consider the first example we need to be cognizant of the fact that we will get 0 when we pass in null using Convert. Seems harmless, but in many cases (as was mine) you’re going to be using that integer in a context where 0 is valid apart from null. Take for example looking up some record from the database based on how that integer gets converted. 0 could be a valid record id which would then cause the code to execute on an unexpected record. Say you were processing a delete request and the id of the record in question is being stored in cache/session. If the cache/session expires before you execute this request it will errantly delete the wrong record. There are countless other potential problems along these same lines if you don’t make sure that nulls are handled in a way consistent with your logic.
So in summary, if you want to protect from invalid integers being passed in and therefore have a higher reliability of data integrity, then you should use Parse. However, if your looking for an easy way to handle nulls and remain aware that these will become 0 then Convert is an easy way to avoid having to check for yourself.
.NET, Programming
C#, Convert, Parse
I learned something very interesting today about the framework. Apparently you can compile non-unique method signatures when you are using params. I was building a custom control and creating an override for DataBind() and I wanted to have 2 versions; one that took parameters, and one that didn’t. So I did the natural thing any developer wanting to do this would do and created the method with 2 seemingly unique signatures:
public override void DataBind()
{
LoadControlData();
}
public void DataBind(params object[] args)
{
LoadControlData(args);
}
This code compiles just fine except something very odd happens when you run it. It is impossible to call the empty method signature! If you call the code like this: UserControl.DataBind(), it will execute the signature with params! So if you had some code in the non-param version of the method that was specific to someone calling in without params (such as calling a different loader) it would never run. It makes little sense that passing nothing to a method that defines a single parameter as a params object[] would work (the CLR actually creates a (not-null) zero length array in this case). The odd part is why this code compiles in the first place since the documentation is very clear that params have no bearing on a method’s signature in terms of making it unique. MSDN C# specs state:
Also, note that the return type and the params modifier are not part of a signature, so it is not possible to overload solely based on return type or on the inclusion or exclusion of the params modifier. As such, the declarations of the methods F(int) and F(params string[]) identified above result in a compile-time error.
This is a little confusing since it the docs compare 2 single parameter signatures as indistinguishable, which makes 100% sense since it’s a one-to-one comparison. However, it’s less obvious that method() and method(params object[]) would also be indistinguishable especially since the compiler has no issues with doing this (not even a warning). The problem is when you try and run it, it will never call the empty method and that’s it. You don’t get a runtime error or anything either… you other method just doesn’t run.
It was an interesting learning experience for me today, that’s for sure!
.NET, Programming
C#, method signatures