Reflection and Dynamic keyword in .NET
In this .NET interview question we will explain Reflection and Dynamic keyword in .NET. View more for practical uses of Reflection and Dynamic keyword in .NET
What is Reflection?
Reflection is needed when you want to determine/inspect contents of an assembly.
For example look at your visual studio editor intellisense, when you type “.” (dot) before any object , it gives you all members of the object.
This is possible because of reflection.
Reflection also goes one step further; it can also invoke a member which is inspected. For instance if the reflection detects that there is a method called as “GetChanges” in an object.
We can get a reference to that method instance and invoke the same on runtime.
In simple words reflection passes through two steps “Inspect” and “Invoke” (optional).
“Invoke” process is optional.
What is Dynamic?
Programming languages can be divided in to two categories strongly typed and dynamically typed. Strongly typed languages are those where the checks happen during compile time while dynamic languages are those where type checks are bypassed during compile time. In dynamic language object types are known only during runtime and type checks are activated only at run time.
So we would like to take advantage of both the world. Because many times we do not know object type until the code is executed. In other words we are looking at something like dynamically statically typed kind of environment. That’s what dynamic keyword helps us with.
If you create a variable using the “Dynamic” keyword and if you try to see members of that object you will get a message as shown below “will be resolved at runtime”.
Now try the below code out. In the below code I have created a dynamic variable which is initialized with a string data. And in the second line I am trying to have fun by trying to execute a numeric incremental operation. So what will happen now?.... think.
Now this code will compile fine without any complains. But during runtime it will throw an exception complaining that the mathematical operations cannot be executed on the variable as it’s a string type. In other words during runtime the dynamic object gets transformed from general data type to specific data type (ex: - string for the below code).
We also have an article on differences between Reflection and Dynamic keyword in .NET
See our following video on VAR vs Dynamic in C#: -