Search code examples
asp.net-mvc-2c#-4.0default-valueoptional-arguments

ASP.NET MVC DefaultValue attribute vs C# Optional Argument


What is the difference between this ASP.NET MVC2 method signature, which uses the DefaultValue attribute:

public ActionResult DoStuff([DefaultValue(MyEnum.Alpha)] MyEnum enumToUse, bool printPage = false)
{
    //...
}

And this signature, which instead uses a C# 4.0 optional argument?

public ActionResult DoStuff(MyEnum enumToUse = MyEnum.Alpha, bool printPage = false)
{
    //...
}

Are the two statements different in any functional way, or is it just a matter of preference?


Solution

  • Same stuff, it's a matter of personal preference. I would use the second as it's less keystrokes. Also I think that the DefaultValueAttribute will involve some reflection voodoo so if you are anal about performance you might prefer the C# 4.0 optional arguments.