Easy way to do Dynamic Type Casting using Reflection in C#. | Converting Type variable to Type

 Some times we might have come across situations where in we are provided with the type information of the object to be instantiated at runtime. In those cases we use the type information to create an object using Reflection, but unfortunately we will not be able to type cast to the desired type since the type information is available to us as a variable.

In those cases we can make use of a generic Cast method and invoke that method during runtime with the help of Reflection. This is also called as Dynamic Type Casting using Reflection. We can see this with the help of an C# code example as shown below:

Code Example for Dynamic Type Casting


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DynamicTypeCasting
{
    public class Consumer
    {
        public string Name { get; set; }
        public int Id { get; set; }
    }

    
    internal class Program
    {
        static void Main(string[] args)
        {
            DynamicTypeCastingExample dtc = new DynamicTypeCastingExample();
            dtc.Execute();
        }
    }

    public class DynamicTypeCastingExample
    {
        internal static IEnumerator<Type> GetTypeInfo()
        {
            var typeInfos = File.ReadAllLines(@"TypeInfo.txt");
            foreach (var typeInfo in typeInfos)
            {
                yield return Type.GetType(typeInfo);
            }
        }

        public void Execute()
        {
            var enumerator = GetTypeInfo();
            while (enumerator.MoveNext())
            {
                var type = enumerator.Current;
                object obj = null;
                try
                {
                    obj = Activator.CreateInstance(type);
                }
                catch(Exception e)
                {
                    throw e;
                }

                //Dynamically cast the object to the specified type using a Generic Method
                //This Generic method can be invoked through reflection
               
                var methodInfo = this.GetType().GetMethod("CastObj").MakeGenericMethod(type);
                var expectedTypeObj = methodInfo.Invoke(null, new object[] { obj });

                //Safely use Reflection to get the properties from the object belonging to the type
                expectedTypeObj.GetType().GetProperty("Name").SetValue(obj, "Consumer1", null);
                var value = expectedTypeObj.GetType().GetProperty("Name").GetValue(obj);
                Console.WriteLine(value);
            }

            Console.ReadKey();
        }

        public static dynamic CastObj<T>(object obj) where T : class
        {
            if (obj is object[] arr)
                return arr.Cast<T>();
            return obj as T;
        }
    }
}

Text File:

Type information as a text file



As shown in the code above I am getting the type information from outside (Text file) and using the type information to create an object using reflection.

Converting Type Variable to Type using Reflection


For converting to the desired type I have defined a generic API called CastObj which is invoked at runtime using reflection. The type information is set in the generic method CastObj using the API MakeGenericMethod and passing in the type information as a parameter. This essentially will convert the type information which is available as a variable to the Type.

Once its converted to its desired type we can try to access the properties defined in that type as shown in the code.

Code provides the output as shown below:

Code execution output for dynamic casting





Comments

Popular posts from this blog

Creating RESTful Minimal WebAPI in .Net 6 in an Easy Manner! | FastEndpoints

Mastering Concurrency with Latches and Barriers in C++20: A Practical Guide for Students

Graph Visualization using MSAGL with Examples