Offir Pe'er Offir Pe'er - 3 months ago 9
C# Question

C# - Send type as parameter and return a type based on it

I have a function that receive a dynamic object and a type as string.
I would like to cast the object to the type I have in my string.

public void PostAutomaticRule(dynamic automaticRuleObject, string ruleType)
{
switch (ruleType)
{
case "Increase_budget":
ConvertToAutomaticRule(typeof(IncreaseBudgetRule), ref automaticRuleObject);
break;
}
}


private void ConvertToAutomaticRule<T>(Type type, ref dynamic ruleObject)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var json = serializer.Serialize(ruleObject);
var c = serializer.Deserialize<type>(json);
}


The class I am trying to convert to:

public class IncreaseBudgetRule
{
public string automaticRuleName { get; set; }
public string givePrioity { get; set; }
}


I have many rules types so I want that function to receive a type and a object and will return an object of the type I sent in the function.
How can I accomplish that?

Answer

You don't need the type in your ConvertToAutomaticRule-Method. You defined there a generic paramter which you can use as the type of the outcome. As the Deserialize-Method also accepts a generic Argument you can rewrite your methods like this:

public void PostAutomaticRule(dynamic automaticRuleObject, string ruleType)
{
    switch (ruleType)
    {
        case "Increase_budget":
            ConvertToAutomaticRule<IncreaseBudgetRule>(ref automaticRuleObject);
            break;
    }
}


private void ConvertToAutomaticRule<T>(ref dynamic ruleObject)
{
    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(ruleObject);
    var c = serializer.Deserialize<T>(json);
}

Edit (returning instead of using ref):

You can also use the generic parameter to set is as return type.

public void PostAutomaticRule(dynamic automaticRuleObject, string ruleType)
{
    switch (ruleType)
    {
        case "Increase_budget":
            var increasedBudgetRule = ConvertToAutomaticRule<IncreaseBudgetRule>(automaticRuleObject);
            break;
    }
}


private T ConvertToAutomaticRule<T>(dynamic ruleObject)
{
    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(ruleObject);
    return serializer.Deserialize<T>(json);
}