Chapter 5. Implementing Dynamic and Reflection

Reflection allows code to look inside of a type and examine its details and members. This is useful for libraries and tools that want to give the user maximum flexibility to submit objects to perform some automatic operation. A common example of code that does reflection are unit testing frameworks. As described in Recipe 3.1, unit tests take classes whose members have attributes to indicate which methods are tests. The unit testing framework uses reflection to find classes that are tests, locate the test methods, and execute the tests.

The example in this chapter is based on a dynamic report-building application. It uses reflection to read attributes of a class, access type members, and execute methods. The first four sections of this chapter show how to do that.

In addition to reflection, another way to work flexibly with code is a C# feature called dynamic. In C#, much of the code we write is strongly typed, and that’s a huge benefit for productivity and maintainability. That said, C# has a dynamic keyword that allows developers to assume that objects have a certain structure. This is much like dynamic programming languages, like JavaScript and Python, where developers access objects based on documentation that specifies what members an object has. So, they just write code that uses those members. Dynamic code allows C# to do the same thing.

When performing operations requiring COM interop, dynamic is particularly useful, and there’s ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.