How To Use Dynamic To Return Different Objects On Runtime In C#

A lot of time you get a requirement to return different kind of object from a single method. Is it possible? Yes there are ways by which you can deliver different objects on run time and dynamic is one of those solution.

Introduction
 
Today, we will understand how to use dynamic keyword to return a whole different object on runtime. You can even change the return type based on your input. For example, based on the user input, the same method can return a four-wheeler object, a two-wheeler object, and other class object on run time.
 
If you know the concept of dynamic in C#, then it would be familiar to you. There is one more related concept, i.e., var keyword in C#. But the difference in var and dynamic is that var gets the object property and methods on compile time while dynamic does it on runtime, which comes as a feature for this concept.
 
Let's start the demo. In our current demo, I am creating a console application using .NET Core framework on Visual Studio 2017. In my application I have created 2 classes, High and Low, where High inherits Low. But you can create any number of classes, either related or non-related. It works everywhere. 
 
So below is my code that I have written for this demo.
  1. using System;  
  2. using System.ComponentModel;  
  3.   
  4.   
  5. namespace MultipleDataProfile  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             bool app = true;  
  12.             while (app)  
  13.             {  
  14.                 Console.WriteLine("\n\nenter the data profile you want to see : High or Low. to close application hit close");  
  15.                 string profile = Console.ReadLine();  
  16.                 if (profile.ToLower().Equals("close"))  
  17.                 {  
  18.                     app = false;  
  19.                 }  
  20.                 else  
  21.                 {  
  22.                     dynamic obj = GetObject(profile);  
  23.                     foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))  
  24.                     {  
  25.                         string name = descriptor.Name;  
  26.                         object value = descriptor.GetValue(obj);  
  27.                         Console.WriteLine("{0}={1}", name, value);  
  28.                     }  
  29.                 }  
  30.   
  31.   
  32.             }  
  33.   
  34.         }  
  35.   
  36.         private static dynamic GetObject(string profile)  
  37.         {  
  38.             if (profile.ToLower().Equals("low"))  
  39.             {  
  40.                 Low low = new Low { Name = "bhavna", FatherName = "FName" };  
  41.                 return low;  
  42.             }  
  43.             else if (profile.ToLower().Equals("high"))  
  44.             {  
  45.                 High high = new High { Name = "Rahul", FatherName = "Rahul Father", Subject = "Maths", DOB = "30112005" };  
  46.                 return high;  
  47.             }  
  48.             else  
  49.             {  
  50.                 return "not a valid option";  
  51.             }  
  52.         }  
  53.   
  54.         class Low  
  55.         {  
  56.             public string Name { getset; }  
  57.             public string FatherName { getset; }  
  58.         }  
  59.         class High : Low  
  60.         {  
  61.             public string Subject { getset; }  
  62.             public string DOB { getset; }  
  63.         }  
  64.   
  65.     }  
  66. }  
In this demo we have written a while loop and until I write close in my input, the application keeps asking for the input for which object to be written  -- High or Low. So we can give 3 valid inputs: High, Low and close. You can see how and where we have used dynamic keyword in our program. Based on input it will return dynamically different objects to us. So let's run the application.
 
How To Use Dynamic To Return Different Objects On Runtime In C# 
 
This is how this program runs. It is asking for 3 inputs: High, Low or close. So let's enter High. Below is the output.
 
 How To Use Dynamic To Return Different Objects On Runtime In C# 
 
Here you see dynamic object is returning High class object. Now I will enter Low as second input.
 
How To Use Dynamic To Return Different Objects On Runtime In C# 
 
Based on our input it has dynamically returned a Low class object. Entering close in input just terminates the application. So this is how we can return multiple different objects dynamically.  
 
Applications of this concept
  1. You can create Web APIs to return different XMLs, JSONs or objects dynamically
  2. You do not need to worry about hiding data based on user role or designation. You can just return different objects based on the role of the user.
  3. You can achieve any similar requirement where object return type needs to be set dynamically. 
Conclusion 
 
Using this concept you do not need to worry about what method will return. We can return different objects dynamically on runtime. I have written one other article to achieve something similar using inheritance and calling the base from the derived class object. But I find this method of using dynamic more reliable while you need to return different objects on runtime.
 
 
If you will compare both the earlier and later methods, you will find this method more reliable and simple.
 
I hope you like this article. Do leave your feedback in the comments.