Aishwarya Shiva
Aishwarya Shiva

Reputation: 3406

Parse object to a dynamically supplied type

I have following generic method in C# that parses client data from an ASP.NET web forms application into some defined type:

public static T ParseClientRequest <T> (object data) 
{
    var t = (System.Collections.Generic.Dictionary<string,object>) data;
    T obj = (T)Activator.CreateInstance(typeof(T));
    foreach(var pair in t) {
        FieldInfo field = obj.GetType().GetField(pair.Key);
        field.SetValue(obj, pair.Value);
    }
    return obj;
}

I have two questions about it:

  1. Is there any efficient way(using LINQ or other) of doing it without using loop? Or is it efficient enough?
  2. The code throws exception if one of the type's field is of type other than string. How the object type can be parsed to a dynamically supplied type?

Upvotes: 1

Views: 106

Answers (1)

Eser
Eser

Reputation: 12546

1- Efficiency is relative. Hard to answer. If it is good enough for you, then no problem

2- You can fix your code by using Convert.ChangeType

public static T ParseClientRequest<T>(object data)
{
    var t = (System.Collections.Generic.Dictionary<string, object>)data;
    T obj = (T)Activator.CreateInstance(typeof(T));
    foreach (var pair in t)
    {
        FieldInfo field = obj.GetType().GetField(pair.Key);
        field.SetValue(obj, Convert.ChangeType(pair.Value, field.FieldType)); //See this line
    }
    return obj;
}

Upvotes: 2

Related Questions