Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C# 4.0

What is the Difference between Reflection and Dynamic Keyword in C#?

Rate me:
Please Sign up or sign in to vote.
4.88/5 (67 votes)
21 Jun 2021CPOL5 min read 171.7K   119   45
Understanding two terminologies - reflection and dynamic keyword
In this article, we will try to understand two terminologies, reflection and dynamic keyword. Many developers get confused between them because both of them help us to do dynamic invocation.

Table of Contents

Introduction

In this article, we will try to understand two terminologies: Reflection and the dynamic keyword. Many developers get confused between them because both of them help us to do dynamic invocation.

In this article, we will try to unleash the differences and see in what scenarios we will use which. But before we start comparing, let's understand each separately and then at the end of the article, we will do a full comparison.

What is Reflection and Why We Need It?

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 the members of the object. This is possible because of Reflection.

Image 1

Reflection also goes one step further; it can also invoke a member which is inspected. For instance, if Reflection detects that there is a method called GetChanges in an object, we can get a reference to that method instance and invoke it on runtime.

In simple words, Reflection passes through two steps: “Inspect” and “Invoke” (optional). The "Invoke" process is optional.

Image 2

 

How Do We Implement Reflection?

Implementing reflection in C# is a two step process , first get the “type” of the object and then use the type to browse members like “methods”, “properties”, etc.

Step 1

The first step is to get the type of the object. So, for example, you have a DLL ClassLibrary1.dll which has a class called Class1. We can use the Assembly (belongs to the System.Reflection namespace) class to get a reference to the type of the object. Later, we can use Activator.CreateInstance to create an instance of the class. The GetType() function helps us to get a reference to the type of the object.

C#
var myAssembly = Assembly.LoadFile(@"C:\ClassLibrary1.dll");
var myType = myAssembly.GetType("ClassLibrary1.Class1");
dynamic objMyClass = Activator.CreateInstance(myType);
// Get the class type
Type parameterType = objMyClass.GetType();

Step 2

Once we have a reference of the type of the object, we can then call GetMembers or GetProperties to browse through the methods and properties of the class.

C#
// Browse through members
foreach (MemberInfo objMemberInfo in parameterType.GetMembers())
{Console.WriteLine(objMemberInfo.Name);}

// Browse through properties.
foreach (PropertyInfo objPropertyInfo in parameterType.GetProperties())
{Console.WriteLine(objPropertyInfo.Name);}

In case you want to invoke the member which you have inspected, you can use InvokeMember to invoke the method. Below is the code:

C#
parameterType.InvokeMember("Display",BindingFlags.Public | 
BindingFlags.NonPublic | BindingFlags.InvokeMethod | 
BindingFlags.Instance,null, objMyClass, null); 

What are the Practical Uses of Reflection?

  • If you are creating an application like a Visual Studio editor where you want to show the internals of an object by using intellisense.
  • If you are creating a unit testing framework. In unit testing frameworks, we need to invoke methods and properties dynamically for testing purpose.
  • Sometimes we would like to dump properties, methods, and assembly references to a file or show it on screen.

What is the Use of the Dynamic Keyword?

Programming languages can be divided into two categories: strongly typed and dynamically typed. Strongly typed languages are those where checks happen during compile time while dynamic languages are those where type checks are bypassed during compile time. In a dynamic language, object types are known only during runtime and type checks are activated only at runtime.

Image 3

We would like to take advantage of both worlds. Because many times, we do not know the object type until the code is executed. In other words, we are looking at something like a dynamically and statically typed kind of environment. That’s what the 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”.

Image 4

Now try the below code out. In the code, I have created a dynamic variable which is initialized with 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....

C#
dynamic x = "c#";
x++;

Now this code will compile fine without any complaints. 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 the general data type to a specific data type (e.g.: string for the below code).

Image 5

 

What are the Practical Uses of the Dynamic Keyword?

One of the biggest practical uses of the dynamic keyword is when we operate on MS Office components via interop.

So, for example, if we are accessing Microsoft Excel components without the dynamic keyword, you can see how complicated the code gets. Lots of casting happening in the below code, right?

C#
// Before the introduction of dynamic.
Application excelApplication = new  Application();
((Excel.Range)excelApp.Cells[1, 1]).Value2 = "Name";
Excel.Range range2008 = (Excel.Range)excelApp.Cells[1, 1];

Now look at how simple the code becomes by using the dynamic keyword. No casting needed and during runtime type checking also happens.

C#
// After the introduction of dynamic, the access to the Value property and 
// the conversion to Excel.Range are handled by the run-time COM binder.
dynamic excelApp = new Application();
excelApp.Cells[1, 1].Value = "Name";
Excel.Range range2010 = excelApp.Cells[1, 1];

What is the Difference between Reflection and Dynamic?

  • Both Reflection and dynamic are used when we want to operate on an object during runtime.
  • Reflection is used to inspect the meta-data of an object. It also has the ability to invoke members of an object at runtime.
  • dynamic is a keyword which was introduced in .NET 4.0. It evaluates object calls during runtime. So until the method calls are made, the compiler is least bothered if those methods / properties exist or not.
  • dynamic uses Reflection internally. It caches the method calls made thus improving performance to a certain extent.
  • Reflection can invoke both public and private members of an object while dynamic can only invoke public members.
  • dynamic is instance specific: you don't have access to static members; you have to use Reflection in those scenarios.

Below is the detailed comparison table which shows in which scenario they are suited:

  Reflection Dynamic
Inspect (meta-data) Yes No
Invoke public members Yes Yes
Invoke private members Yes No
Caching No Yes
Static class Yes No

Below is a simple diagram which summarizes visually what Reflection can do and what the dynamic keyword can do.

Image 6

For further reading, do watch the below interview preparation videos and step by step video series:

History

  • 16th May 2013: Initial version
  • 22nd June, 2021: Updated

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
QuestionComparison table explaination Pin
Member 1313459717-Sep-18 21:12
Member 1313459717-Sep-18 21:12 
QuestionGreat Article!! Pin
RBSHARMA24-Apr-17 23:45
RBSHARMA24-Apr-17 23:45 
QuestionEXCELLENT ARTICLE Pin
frikrishna14-May-16 4:28
frikrishna14-May-16 4:28 
QuestionNice Article Pin
Naz_Firdouse11-Aug-14 0:04
Naz_Firdouse11-Aug-14 0:04 
GeneralMy vote of 5 Pin
Marla Sukesh16-Oct-13 8:14
professional Marla Sukesh16-Oct-13 8:14 
QuestionExcellent Share Pin
Sunny_Kumar_15-Oct-13 18:31
Sunny_Kumar_15-Oct-13 18:31 
AnswerNice Pin
DhavalRana15-Oct-13 18:10
DhavalRana15-Oct-13 18:10 
GeneralMy vote of 5 Pin
Mayank.Gupta3-Jul-13 4:26
Mayank.Gupta3-Jul-13 4:26 
GeneralMy vote of 5 Pin
Monjurul Habib11-Jun-13 7:50
professionalMonjurul Habib11-Jun-13 7:50 
GeneralMy vote of 5 Pin
Renju Vinod29-May-13 0:02
professionalRenju Vinod29-May-13 0:02 
GeneralRe: My vote of 5 Pin
Shivprasad koirala29-May-13 2:08
Shivprasad koirala29-May-13 2:08 
GeneralUsing dynamics Pin
AlexMortola28-May-13 10:05
professionalAlexMortola28-May-13 10:05 
GeneralMy vote of 5 Pin
S. M. Ahasan Habib28-May-13 8:18
professionalS. M. Ahasan Habib28-May-13 8:18 
GeneralRe: My vote of 5 Pin
Shivprasad koirala28-May-13 8:57
Shivprasad koirala28-May-13 8:57 
GeneralMy vote of 5 Pin
jawed.ace27-May-13 2:48
jawed.ace27-May-13 2:48 
GeneralRe: My vote of 5 Pin
Shivprasad koirala28-May-13 8:57
Shivprasad koirala28-May-13 8:57 
GeneralMy vote of 5 Pin
SRIRAM 223-May-13 18:48
SRIRAM 223-May-13 18:48 
GeneralRe: My vote of 5 Pin
Shivprasad koirala23-May-13 18:51
Shivprasad koirala23-May-13 18:51 
Questionnice Pin
BillW3323-May-13 11:20
professionalBillW3323-May-13 11:20 
AnswerRe: nice Pin
Shivprasad koirala23-May-13 16:19
Shivprasad koirala23-May-13 16:19 
GeneralMy vote of 4 Pin
Rockstar_23-May-13 1:45
professionalRockstar_23-May-13 1:45 
GeneralRe: My vote of 4 Pin
Shivprasad koirala23-May-13 6:28
Shivprasad koirala23-May-13 6:28 
QuestionExcellent, My vote of 5 Pin
Atal Upadhyay20-May-13 19:12
Atal Upadhyay20-May-13 19:12 
AnswerRe: Excellent, My vote of 5 Pin
Shivprasad koirala21-May-13 18:17
Shivprasad koirala21-May-13 18:17 
Question[My vote of 2] What is behind the Dynamic type? Pin
AndyVGa17-May-13 9:36
professionalAndyVGa17-May-13 9:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.