1pgjy
1pgjy

Reputation: 159

Convert enum? to int? fails when using reflection

It succeed when using int? to convert.
It failed when using reflection to convert.
How can I assign value enum? to property int? successful using reflection?

static void Main(string[] args)
{
    Dc dc = new Dc { Solution = Solution.Upgrade };

    Model model = new Model {  };

    //assign by reflection
    var psolution = model.GetType().GetProperty("Solution");
    //psolution.SetValue(model, dc.Solution); //this fail
    model.Solution = (int?)dc.Solution; //this success
    psolution.SetValue(model, Convert.ChangeType(dc.Solution, psolution.PropertyType)); //this fail
}

class Dc
{
    public Solution? Solution { get; set; }
}

class Model
{
    public int? Solution { get; set; }
}

enum Solution
{
    Upgrade = 1,
    Discard = 2,
}

Upvotes: 1

Views: 95

Answers (1)

Vidmantas Blazevicius
Vidmantas Blazevicius

Reputation: 4812

Try this:

Type t = Nullable.GetUnderlyingType(psolution.PropertyType) ?? psolution.PropertyType;
object safeValue = (dc.Solution == null) ? null : Convert.ChangeType(dc.Solution, t);
property.SetValue(model, safeValue, null);

You need to get the underlying type parameter of Nullable<T> in order to set the value for the int?.

Upvotes: 3

Related Questions