C# 4.0 is a version of the C# programming language that was released on April 11, 2010. Microsoft released the 4.0 runtime and development environment Visual Studio 2010. The major focus of C# 4.0 is interoperability with partially or fully dynamically typed languages and frameworks, such as the Dynamic Language Runtime and COM.
The following new features were added in C# 4.0.
A new pseudo-type dynamic
is introduced into the C# type system. It is treated as System.Object
, but in addition, any member access (method call, field, property, or indexer access, or a delegate invocation) or application of an operator on a value of such type is permitted without any type checking, and its resolution is postponed until run-time. This is known as duck typing. For example:
Dynamic method calls are triggered by a value of type dynamic
as any implicit or explicit parameter (and not just a receiver). For example:
Dynamic lookup is performed using three distinct mechanisms: COM IDispatch for COM objects, IDynamicMetaObjectProvider
DLR interface for objects implementing that interface, and reflection for all other objects. Any C# class can therefore intercept dynamic calls on its instances by implementing IDynamicMetaObjectProvider
.
In case of dynamic method and indexer calls, overload resolution happens at run-time according to the actual types of the values passed as arguments, but otherwise according to the usual C# overloading resolution rules. Furthermore, in cases where the receiver in a dynamic call is not itself dynamic, run-time overload resolution will only consider the methods that are exposed on the declared compile-time type of the receiver. For example:
Any value returned from a dynamic member access is itself of type dynamic
. Values of type dynamic
are implicitly convertible both from and to any other type. In the code sample above this permits GetLength
function to treat the value returned by a call to Length
as an integer without any explicit cast. At run time the actual value will be converted to the requested type.