Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get System.Type from "System.Drawing.Color" string

I have an xml stored property of some control

<Prop Name="ForeColor" Type="System.Drawing.Color" Value="-16777216" />

I want to convert it back as others

System.Type type = System.Type.GetType(propertyTypeString);
object propertyObj = 
  TypeDescriptor.GetConverter(type).ConvertFromString(propertyValueString);

System.Type.GetType("System.Drawing.Color") returns null.

The question is how one can correctly get color type from string

(it will be better not to do a special case just for Color properties)

Update

from time to time this xml will be edited by hand

like image 939
jonny Avatar asked Feb 28 '23 16:02

jonny


1 Answers

You need to specify the assembly as well as the type name when using Type.GetType(), unless the type is in mscorlib or the currently executing assembly.

If you know it's in the System.Drawing assembly, you can use Assembly.GetType() instead - or perhaps look in a whole list of possible assemblies:

Type type = candidateAssemblies.Select(assembly => assembly.GetType(typeName))
                               .Where(type => type != null)
                               .FirstOrDefault();

if (type != null)
{
    // Use it
}
else
{
    // Couldn't find the right type
}
like image 198
Jon Skeet Avatar answered Mar 12 '23 11:03

Jon Skeet