What's new in C#4 - A Quick Summary

Named and optional (default value) parameters.
Default value is perhaps a questionable language feature (can be a source of bugs - for example, Java doesn't have it) - however it is handy for working with MS Office automation.

.NET dynamic keyword: for working with dynamic (not statically typed) languages like Python or Javascript (prototyped ).
ExpandoObject - like javascript, we can add members dynamically - the difference is that if we attempt to access a missing property, C# throws exception, where javascript would return undefined.

.NET 4 fixes in generic typing:

Covariance -
from specific (Employee or 'e') to less specific (Person or 'p')
example: return types in different Func refs.

Func<employee> fe = null;
Func<person> fp = fe; //error in C# 3.5

Contravariance -
from less specific to more specific types. This was not fully supported in previous versions of C# (2, 3, 3.5) with generic delegates.
Example: parameter type in different Action refs:

Action<person> pa = null;
Action<employee> ea = pa; //error in C# 3.5

These fixes have been made by Microsoft where safe to do so: for example, IEnumerable is fixed.
List<t> class not fixed, since this could cause runtime problems:
e.g. adding a Person to a collection of Employees!

List<employee> es = new List<employee>();
es.Add(new Employee());
List<person> ps = es; //error in C# 4 - this is correct, see next line:
ps.Add(new Person()); //es would be a list of Employee and of Person types!

Comments