Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Default Parameters

This is, probably, a very simple answer for someone. I have a method with an Optional Parameter like so;

public static Email From(string emailAddress, string name = "")
    {
        var email = new Email();
        email.Message.From = new MailAddress(emailAddress, name);
        return email;
    }

Now, I must target .Net 3.5 and it was my understanding that Optional Parameters are part of .Net 4. However, my project builds and I double checked the Properties - Application page which states 3.5 as the target framework. Then I found a article on MSDN saying it's a feature of C#4 in VS2010. (MSDN Article --> Named and Optional Arguments)

Can someone help clarify this for me. C#4 does not require .Net4? What are Optional Parameters ACTUALLY a part of?

Thank you.

like image 506
Refracted Paladin Avatar asked Aug 30 '10 16:08

Refracted Paladin


2 Answers

Optional parameters have been supported in the CLR since 1.0. Languages like VB.Net's have been using them since the start. While the first version of C# to support them is 4.0, it can still generate valid code for a 2.0 CLR and in fact does so. Hence you can use default parameters in 2010 if you are targeting the 3.5 CLR (or 2.0, 3.0, etc ...)

This type of support is not limited to default parameters. Many new C# features can be used on older version of the framework because they do not rely on CLR changes. Here are a few more which are supported on CLR versions 2.0 and above

  • Named Arguments: Added C# 4.0
  • Lambda Expressions: Added C# 3.0
  • Auto Properties: Added C# 3.0
  • Extension Methods: Added C# 3.0
  • Co/Contra Variance: Added C# 4.0
like image 200
JaredPar Avatar answered Nov 15 '22 21:11

JaredPar


If you compile that up and examine the output using a tool like ILDASM you'll see that the optional parameter is simply implemented by adding an attribute to the metadata that describes the method's formal parameters. As long as that attribute class is available on the target platform there should be no problem with using the emitted code on a downlevel platform.

like image 22
Eric Lippert Avatar answered Nov 15 '22 21:11

Eric Lippert