Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Holy Reflection

I'm receiving an error, "unable to convert string to int?". Which I find odd, I was under the notion when you utilize PropertyInfo.SetValue it should indeed attempt to use that fields type.

// Sample:
property.SetValue(model, null, null);

The above would attempt to implement default(T) on the property according to PropertyInfo.SetValue for the Microsoft Developer Network. However, when I implement the following code:

// Sample:
property.SetValue(model, control.Value, null);

The error bubbles, when I implement a string for a property that should have an int?, I was under the notion that it would attempt to automatically resolve the specified type. How would I help specify the type?

// Sample:
PropertyInfo[] properties = typeof(TModel).GetProperties();
foreach(var property in properties)
     if(typeof(TModel).Name.Contains("Sample"))
          property.SetValue(model, control.Value, null);

Any clarification and how to resolve the cast would be helpful. The sample has been modified for brevity, trying to provide relevant code.

like image 492
Greg Avatar asked Oct 20 '22 02:10

Greg


1 Answers

You have to convert the control value to the type which the property is using Convert.ChangeType():

if(typeof(TModel).Name.Contains("Sample"))  
   property.SetValue(model, Convert.ChangeType(control.Value, property.PropertyType), null);

UPDATE:

In your case it is Nullable type (Nullable<int>) so you have to do it different way as Convert.ChangeType() in normal not works on Nullable types:

if(typeof(TModel).Name.Contains("Sample"))
{ 
  if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
  {
     property.SetValue(model,Convert.ChangeType(control.Value, property.PropertyType.GetGenericArguments()[0]),null);
  }
  else
  {
    property.SetValue(model, Convert.ChangeType(control.Value, property.PropertyType), null);
  }
like image 168
Ehsan Sajjad Avatar answered Oct 31 '22 16:10

Ehsan Sajjad