Thursday, May 21, 2015

C# Named Arguments

Intro

Whose turn is it to take out the trash? What's the answer to everything? Is Bieber better or is One Direction? Team Jacob or the pasty one? These are some great examples of named arguments.

Wait, what's that? Oh, that's not the kind of named arguments you care to read about? Ok fine. For the record, it's clearly 42, but we'll move on to C# named arguments.



The code sample is in VS 2013 .Net 4.5. Named arguments have been around since VS2010 though so you can follow along with older versions.

Que?

I'm sure you've all seen optional parameters in C# by now. Just in case you haven't, here's an example:

namespace NamedArgumentsBlog
{
    public class Class1
    {
        public void OptionalParams(int param1, int? param2 = null, string param3 = "")
        {
            //do stuff here
        }

        public void CallMethods()
        {
            //call with all params
            OptionalParams(1, 33, "fred");
            //Call with the required and 1 optional param
            OptionalParams(-12, 0);
        }
    }
}


The method OptionalParams has 3 parameters. The first one is required because it has no default value. 2nd and 3rd parameters are optional; if a caller doesn't specify a value for a parameter, it gets the default value. But hey you already knew this stuff, so let's see what we can do with named arguments.

Here's another sample. This uses the same class and the same 2 methods, but with a slight twist. Starting at line 17, we call the OptionalParams method a couple times, specifying which argument we are populating based on the name of the param rather than using ordering to implicitly specify params. Neat!

namespace NamedArgumentsBlog
{
    public class Class1
    {
        public void OptionalParams(int param1, int? param2 = null, string param3 = "")
        {
            //do stuff here
        }

        public void CallMethods()
        {
            //call with all params
            OptionalParams(1, 33, "fred");
            //Call with the required and 1 optional param
            OptionalParams(-12, 0);
            //call with named params in order
            OptionalParams(param1: 44, param2: 21);
            //call with named params out of order
            OptionalParams(param3: "blah", param1: 42);
        }
    }
}


Simple eh? You just specify the name of the parameter and the value of the parameter, separated by a colon. I must admit I don't use this trick very much, but it's another tool in yer shed. Use wisely.

Resources

Named and Optional Arguments (C# Programming Guide)

No comments:

Post a Comment