Search code examples
c#reflectioncasting

Casting PropertyInfo.GetValue() to a type, when the type is non-nullable


Consider this example code:

var properties = c.GetType().GetProperties();
// note that c is a System.Windows.Forms.Control

foreach( var p in properties )
{
     if (p.PropertyType.Name.Contains("Color") )
     {
         var colour_value = p.GetValue(c,null);
                            
         // I need to cast colour_value to a Color 
     }
}

I need to cast the output from p.GetValue(c, null) to a System.Drawing.Color. I've seen other questions where, in a similar situation, people have suggested either:

(Color) p.GetValue(c, null) 

or

p.GetValue(c, null) as Color

but these don't work because Color is a non-nullable value type. It therefore throws compiler error CS0077.

Is there any way to do this, please?


Solution

  • check property type by comparing exact type, not by name, then do a type cast. System.Drawing.Color is a sctruct and value cannot be null

    var properties = c.GetType().GetProperties();
    
    foreach(var p in properties)
    {
         if (p.PropertyType == typeof(System.Drawing.Color))
         {
             var colour_value = (System.Drawing.Color) p.GetValue(c);
         }
    }