Sunday 24 March 2013

C# syntactic sugar - the params keyword

This is the second in what might soon be a series of blogposts on C# syntactic sugar - that is, where the language allows you to express your intent using a keyword, and the compiler restructures the code to perform how you expect it to.

The params Keyword

This post is about the params keyword. This keyword allows you to define an array parameter to a method, which can be specified by its caller as a list of values. Here's an example that demonstrates the flexible nature of the parameter:
        public static void Main(string[] args)
        {
            // All valid calls
            DoStuff();
            DoStuff(1);
            DoStuff(1, 2);
            DoStuff(new[] { 1, 2 });
        }

        private static void DoStuff(params int[] ints)
        {
            // this method intentionally left blank
        }

The IL

So, what does the compiler does with this? Here's the IL that the compiler produces for the DoStuff method, with the interesting bit highlighted:

.method private hidebysig static void DoStuff(int32[] ints) 
cil managed 
{
 .param [1]
 .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 )
 // Code size 2 (0x2)
 .maxstack 8
 IL_0000: nop
 IL_0001: ret
} // end of method Program::DoStuff

The Compiler

So, the code that the compiler is actually producing looks like this:

        private static void DoStuff([System.ParamArray] int[] ints){
            // this method intentionally left blank
        }

However if you try to compile this code, the C# compiler gives this message:


Clearly this is more than syntactic sugar, it's a requirement!

No comments:

Post a Comment