Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C# 4.0 backward compatible to C# 2.0?

Tags:

c#

c#-4.0

c#-2.0

May I know what is the difference between C# 4.0 and C# 2.0? Is C# 4.0 backward compatible to C# 2.0?

Can I say that C# 4.0 is a superset of C# 2.0 (just like what C++ is to C)?

Thanks.

like image 610
CMW Avatar asked May 16 '10 10:05

CMW


2 Answers

C# 4.0 is nearly backwards compatible with previous versions but there are a few breaking changes. For most ordinary code you won't notice these breaking changes.

For the new features in C# 4 you can check out the Wikipedia article which has quite a good summary with examples. The key points are:

  • Dynamic member lookup
  • Covariant and contravariant generic type parameters
  • Optional ref keyword when using COM
  • Optional parameters and named arguments
  • Indexed properties

Also remember that there was another version in between - C# 3.0. One of the most important additions here is LINQ and all the features added to make it possible. The difference between C# 2.0 and 3.0 is much greater than the difference between C# 3.0 and 4.0.


By the way, not all valid C code is valid C++ as you implied in your question. See here:

In the strict mathematical sense, C isn't a subset of C++. There are programs that are valid C but not valid C++ and even a few ways of writing code that has a different meaning in C and C++.

like image 65
Mark Byers Avatar answered Oct 23 '22 03:10

Mark Byers


There are some subtle breaking changes, as there have been in previous versions. The problem is that C# 4 introduces a new type of valid conversion due to covariance/contravariance. This means that some methods which would previously have not been applicable are now applicable for a particular call. Here's some code which is valid for both C# 4 and C# 2 / 3:

using System;
using System.Collections.Generic;

public class Base
{
    public void DoSomething(IEnumerable<string> strings)
    {
        Console.WriteLine("Base");
    }
}

public class Derived : Base
{
    public void DoSomething(IEnumerable<object> objects)
    {
        Console.WriteLine("Derived");
    }
}

public class Test
{
    static void Main()
    {
        Derived d = new Derived();
        d.DoSomething(new List<string>());
    }
}

In C# 4, this will print "Derived" - in C# 2 and 3 it will print "Base".

The same sort of issue occurred between C# 1 and 2, where delegate instance expressions allowed nongeneric covariance and contravariance.

Any new conversions are pretty much bound to create this sort of issue. In my experience, however, these things are unlikely to actually cause a problem.

Additionally, C# 4 handles locking and field-like events in a slightly different way - again, this won't affect most code, but it's worth knowing about. Chris Burrows has a series of articles on the changes in his blog.

like image 40
Jon Skeet Avatar answered Oct 23 '22 03:10

Jon Skeet