Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Argument code compiles in .NET 3.5. Why?

This piece of code compiles OK in VS 2010 in a framework 3.5 project (I triple checked that)

    public LoggingClient(string uri = "net.msmq://localhost/logging"){...}

Why? I see nothing in the C# 4 spec (doc version), section 21.1, that says this should be backwardly compatible. How is it that I get no compilation error? Will this fail silently in some circumstances?

like image 416
Andrew Matthews Avatar asked Jul 09 '10 02:07

Andrew Matthews


People also ask

Why are optional parameters added?

Optional Parameters are parameters that can be specified, but are not required. This allows for functions that are more customizable, without requiring parameters that many users will not need.

What are optional arguments in C#?

Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.

Should we use optional parameter?

It depends on what your code is doing. If there are sensible defaults then you should use optional parameters but if there are no sensible defaults then adding optional parameters will make your code more complicated.

How are optional parameters implemented in C#?

To implement the optional parameter first you need to add System. Runtime. InteropServices namespace in your program, then creates an optional parameter using the Optional keyword enclosed in square brackets before the definition of the parameter in the method.


2 Answers

Project + Properties, Build tab, scroll down, Advanced. You can change the Language Version to "C# 3.0" if you prefer to maintain source code compatibility.

But yes, you are using the C# 4.0 compiler in VS2010, regardless of the target .NET version you use. The output of the compiler, IL, hasn't changed in .NET 4.0. No, you can't use dynamic, it requires a .NET 4.0 only support assembly (Microsoft.CSharp.dll)

like image 80
Hans Passant Avatar answered Nov 04 '22 13:11

Hans Passant


Optional parameters are merely syntactic sugar - if you don't specify it at the call site, the compiler fills it the default value. There's no dependancy on the .NET framework itself to do anything.

See also Can you use optional parameters in code targeting .NET 3.5?

like image 20
Anon. Avatar answered Nov 04 '22 11:11

Anon.