views:

1463

answers:

6

I'm looking to write a library that uses the new optional parameters feature of C# 4.0, but I want to target it to the 3.5 version of th framework. Is this possible? Are optional parameters syntactic sugar in the same way that Extension Methods are?

+2  A: 

I don't have VS2010 installed here to check, but I believe this would be purely a language feature, and therefore should be usable regardless of the framework being targeted.

Edit: Looking at this link (and a few others), it appears that optional parameters compile to method arguments with an [opt] attribute in the il. I don't know if this parameter existed in previous versions of the clr, but still my guess would be that it does.

Timothy Carter
Yeah, I would think that this is the case, but I don't want to go through installing VS2010 when it isan't RTM yet if it doesn't give this to me.
Charles Graham
C# 4.0 reuses the attribute that VB uses for that purpose, so it has been around since 1.0.
Pavel Minaev
+1  A: 

VB.NET has optional parameters if you want to use optional parameters in .NET 3.5.

Joe Chung
Yeah, I know. I love Optional parameters but hate VB. ;) Plus, having an app in 2 languages is kind of a kludge if you only need VB stuff for one or two classes.
Charles Graham
+4  A: 

Like everyone else, I expected this to work out of the box.

However, actually trying it in VS2010b1, it doesn't appear to work. It looks like setting the framework to .NET 3.5 sets the language level to 3.0 at the moment.

In the "Advanced" bit of the "Build" settings tab, for a .NET 3.5 project the only options are "ISO-1", "ISO-2" and "C# 3.0" - not "default" which is selected for a .NET 4.0 project.

Interestingly enough, a .NET 2.0 project (even with "C# 3.0" selected as the language version) gives a different set of errors to the a .NET 3.5 project... it gives the "I don't understand your syntax" kind of errors instead of "Feature 'optional parameter' cannot be used because it is not part of the 3.0 C# language specification".

It's possible that it would work from the command line, but targeting a different framework version from the command line is non-trivial - I may try later.

Jon Skeet
+2  A: 

With VS2010 RC, I was able to create a .NET 3.5 application that uses optional parameters in C#.

So yes, it's all about syntactic sugar.

Bernard Vander Beken
+2  A: 

VS 2010 supports optional parameters in C# for .NET 3.5 solutions. One caveat however, is that the command-line compiler will report errors.

So, if you have automated builds in running, - using NANT or something else using the command-line compiler - your builds will fail.

demius
A: 

Like Jon Skeet I was getting "Feature 'optional parameter' cannot be used because it is not part of the 3.0 C# language specification". However in the RTM version of Visual Studio you can select Language Version to "default" in Project Properties->Build->Advanced. That got it to work for me.

Lee Richardson