Dynamic Object in C#

Introduction

Dynamic is a new keyword , which is include in c# 4.0 version in 2010. Dynamic keyword manage by the Dynamic Language Runtime (DLR), which work as a Common Language Runtime (CLR). Dynamic object  operate by the dynamic object class and this class manage, How to perform those operation. Dynamic object compile on entirely runtime.

Program

Suppose you want to create  an object which call to same name function of different classes. Then you create single dynamic object which concerned class's objects. This dynamic object call to same name function which use in different classes. See in below example:

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Text; 

namespace dynamic_object_in_c_sharp

{

    public class cat             //Create class cat

    {

        public void run()       // Create Function run()

        {

            Console.WriteLine("Running cat");

        }

    }

 

    public class rat             //Create another class rat

    {

        public void run()        //Create same name function run(), which is in class cat

        {

            Console.WriteLine("running ret");

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

                                    

            cat c = new cat();  //Create object of class cat

            rat r = new rat();  //Create object of class cat

 

            InTheForest(c);     //InTheForeat method has a dynamic parameter  

            InTheForest(r);

        }

        public static void InTheForest(dynamic obj) //concerned of the objects

        {

            obj.run();         //InTheForest method invoke the run method

        }

    }

 

}

 

Output

output.jpg

Ebook Download
View all
Learn
View all