Exploring internal implementation of C# 4.0 Default and Optional arguments

I wanted to explore how C#  compiler has implemented the optional and the default parameter. So here is the sample code that I wrote to verify.

using System;
namespace OptionalTest {
 internal class Program {
 private static void Main(string[] args) {
 var p = new Program();
 Test();
 }
 private static void Test(int x = 10) {
 Console.WriteLine(x);
 }
 }
}

As you can see the default parameter value for x is 10 and it is an optional parameter. After compiling the source code the next step was to disassemble with Reflector.

private static void Test([Optional, DefaultParameterValue(10)] int x){
Console.WriteLine(x);
}

Now it makes sense, looks like the C# compiler emits a custom attribute for System.Runtime.InteropServices.OptionalAttribute which marks the method to have an optional argument and the DefaultParameterValue stores the default value for the parameter. The next step was to disassemble the caller of this function.

And here is the disassembled Main method using reflector

private static void Main(string[] args)
{
Program p = new Program();
Test(10);
}

Notice we didn’t include 10 as an argument to method Test. So the compiler notices that the calling code does not have value for the argument and copies the value from the DefaultParameterValue and sticks it in.

About Naveen
Write code.

2 Responses to Exploring internal implementation of C# 4.0 Default and Optional arguments

  1. Marc Brooks says:

    The big take-away here is that recompiling the code will pick up new defaults values ONLY when the calling code is recompiled. Merely deploying a new assembly for the callee will NOT change the behavior of the previously compiled callers.

    • Naveen says:

      Yes you are right ,this is very similar to constants.

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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: