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

Introduction

Today, we will understand how to use dynamic keywords 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., the var keyword in C#. But the difference between 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 two 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 the code that I have written for this demo.

using System;
using System.ComponentModel;

namespace MultipleDataProfile
{
    class Program
    {
        static void Main(string[] args)
        {
            bool app = true;
            while (app)
            {
                Console.WriteLine("\n\nEnter the data profile you want to see: 'High' or 'Low'. To close the application, type 'close'");
                string profile = Console.ReadLine();
                if (profile.ToLower().Equals("close"))
                {
                    app = false;
                }
                else
                {
                    dynamic obj = GetObject(profile);
                    foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
                    {
                        string name = descriptor.Name;
                        object value = descriptor.GetValue(obj);
                        Console.WriteLine("{0}={1}", name, value);
                    }
                }
            }
        }

        private static dynamic GetObject(string profile)
        {
            if (profile.ToLower().Equals("low"))
            {
                Low low = new Low { Name = "bhavna", FatherName = "FName" };
                return low;
            }
            else if (profile.ToLower().Equals("high"))
            {
                High high = new High { Name = "Rahul", FatherName = "Rahul Father", Subject = "Maths", DOB = "30/11/2005" };
                return high;
            }
            else
            {
                return "Not a valid option";
            }
        }

        class Low
        {
            public string Name { get; set; }
            public string FatherName { get; set; }
        }

        class High : Low
        {
            public string Subject { get; set; }
            public string DOB { get; set; }
        }
    }
}

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 three valid inputs: High, Low, and close. You can see how and where we have used dynamic keywords 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 three 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 that a dynamic object is returning a high-class object. Now, I will enter Low as a 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 Dynamic Keywords

  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 return different objects based on the role of the user.
  3. You can achieve any similar requirement where the 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 when you need to return different objects on runtime.

Earlier method for same functionality >> How To Return Different Types Of Objects In C# Based On A Input Parameter Type

If you 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.


Similar Articles