Chapter 4. C# 4: Improving interoperability

 

This chapter covers

  • Using dynamic typing for interoperability and simpler reflection
  • Providing default values for parameters so the caller doesn’t need to specify them
  • Specifying names for arguments to make calls clearer
  • Coding against COM libraries in a more streamlined fashion
  • Converting between generic types with generic variance

C# 4 was an interesting release. The most dramatic change was the introduction of dynamic typing with the dynamic type. This feature makes C# statically typed (for most code) and dynamically typed (when using dynamic) in the same language. That’s rare within programming languages.

Dynamic typing was introduced for interoperability, but that’s turned out not to be relevant in many developers’ day-to-day work. The major features in other releases (generics, LINQ, async/await) have become a natural part of most C# developers’ toolkits, but dynamic typing is still used relatively rarely. I’m sure it’s useful to those who need it, and at the very least it’s an interesting feature.

The other features in C# 4 also improve interoperability, particularly with COM. Some improvements are specific to COM, such as named indexers, implicit ref arguments, and embedded interop types. Optional parameters and named arguments are useful with COM, but they can also be used in purely managed code. These two are the features from C# 4 that I use on a daily basis.

4.1. Dynamic typing

4.2. Optional parameters and named arguments

4.3. COM interoperability improvements

4.4. Generic variance

Summary