- Dynamic Typed Objects
- Optional and Named Parameters
- Improved COM Interoperability
- Co- and Contra-Variance
Dynamic lookup
Dynamic lookup allows you to write method, operator and indexer
calls, property and field accesses, and even object invocations which
bypass the C# static type checking and instead gets resolved at runtime.
object calc = GetCalculator();
Type type = calc.GetType();
object result = type.InvokeMember(
"Add",
BindingFlags.InvokeMethod,
null,
new object[] { 10, 20 });
int sum = Convert.ToInt32(result);
With the C# 4.0 we would simply write the following code:
dynamic calc = GetCalculator();
int sum = calc.Add(10, 20);
In the above example we are declaring a variable, calc, whose static type is dynamic. We'll then be using dynamic method invocation to call the Add method and then dynamic conversion to convert the result of the dynamic invocation to a statically typed integer.
Named and optional parameters
Parameters in C# can now be specified as optional by providing a
default value for them in a member declaration. When the member is
invoked, optional arguments can be omitted. Furthermore, any argument
can be passed by parameter name instead of position.
public StreamReader OpenTextFile(
string path,
Encoding encoding = null,
bool detectEncoding = false,
int bufferSize = 1024) { }
COM specific interop features
Dynamic lookup as well as named and optional parameters both help
making programming against COM less painful than today. On top of that,
however, we are adding a number of other small features that further
improve the interop experience.
When you work with COM interop methods, you had to pass a reference to Missing.Value for unneeded parameters, like the following:
object filename = "test.docx";
object missing = System.Reflection.Missing.Value;

Join the conversation! Your thoughts help the community grow.