Prakash Bhatia
Prakash Bhatia

Reputation: 243

Named and Optional Parameters work in .NET 2.0

I created a console project in Visual Studio 2010 with .Net Framework 2.0 selected

namespace ConsoleApp1
{
  class Program
  {
    public int Add(int a, int b = 0, int c = 0)
    {
      Console.WriteLine("a is " + a);
      Console.WriteLine("b is " + b);
      Console.WriteLine("c is " + c);
      return a + b + c;
    }

    public static void Main()
    {
      Program o = new Program();
      Console.WriteLine(o.Add(10));
      Console.WriteLine(o.Add(10, 10));
      Console.WriteLine(o.Add(10, 10, 10));
      Console.WriteLine(o.Add(b: 20, a: 10));
      Console.ReadLine();
    }
  }
}

It works successfully.

However the same code if I type in Visual Studio 2008, it fails!.

Could anyone please help me with this issue as Named and Optional Parameters came with C#4 ?

Upvotes: 2

Views: 2587

Answers (3)

DaveShaw
DaveShaw

Reputation: 52788

This is because Named Parameters are a feature of the C# language, not the .net runtime.

Your VS2010 uses the C# 4.0 compiler, VS2008 uses C# 3.0.

This means you can use newer features of the language against an older runtime library.

You can even use Linq (lamda syntax) in .Net 2.0 and VS 2010 if you implement the Linq methods your self (see the Linq Bridge project - this post also has a more indepth discussion as to how it all works).

Upvotes: 7

Marc Gravell
Marc Gravell

Reputation: 1062502

DaveShaw has explained named/optional parameters. You also mention (comments) contravariance and covariance - they are different: covariance and contravariance requires both compiler changes and library changes - IEnumerable<T> became IEnumerable<out T>, etc. That is why they don't work on older .NET versions even with new compilers.

So basically:

  • if the feature you want is implemented entirely in the compiler, it will probably work on older .NET versions as long as you use a newer compiler
  • if the feature you want requires BCL changes, it will probably only work on later .NET versions
    • unless that feature can actually be implemented entirely by additional libraries - in particular via extension methods. As an example, LINQ-to-Objects can work on older .NET versions (with newer C# versions) by adding LINQBridge; similarly, Microsoft.Bcl.Async adds types to some pre-4.5 frameworks allowing async/await to be used

Upvotes: 3

Dan Puzey
Dan Puzey

Reputation: 34200

I think you are confusing .NET versions and C# versions. If you compile using Visual Studio 2010, you are using the C#4 compiler. That's regardless of the version of the .NET framework you're referencing.

The feature you're using is tied to the compiler version not the framework version, and so your code fails to compile in VS2008 (and will succeed in VS2010 regardless of target framework version).

Upvotes: 1

Related Questions