Optional Argument code compiles in .NET 3.5. Why?

北城以北 提交于 2019-12-07 04:27:51

问题


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?


回答1:


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)




回答2:


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?



来源:https://stackoverflow.com/questions/3209433/optional-argument-code-compiles-in-net-3-5-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!