>Obviously the system does this for deserialization. So how can I do it
>for arbitrary classes (not just enums)?

Signature
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Mattias Sjögren wrote:
>>Obviously the system does this for deserialization. So how can I do it
>>for arbitrary classes (not just enums)?
>
> Type.GetType() or Assembly.GetType(). Since there can be multiple
> types with the same name in different assemblies, you need to specify
> which asembly to look in one way or another.
Sorry, I guess I'm a bit dense. I understand that
Type.GetType("System.Drawing.Color") will give me a Type object with all
the info about that class, but how can I use a Type object to actually
*create an instance* of that class? In my example above I suppose I
could get the PropertyInfo for the static property
System.Drawing.Colors.Red, but I'm not sure that is a generic solution
for all constant expressions of all types. I'm looking for a generic
solution to produce an instance of a constant given that constant
expression as a string and the type, like for example:
Class String Constant expression string
============ ======
"System.Drawing.Color" "Red"
"System.Int32" "0x0f"
"MyOwnClass.PiDouble" "3.14"
etc.
As far as I can see, if you want to call a method/property on an
instance via reflection, the instance has to already be created. I
suppose I could make my own factory to parse expressions and figure out
how to create them, it just seems like .NET already has that somewhere.
Either that or I have a poor understanding of the problem, which could
very well be.
-- kov
Nathan Baulch - 31 Jan 2005 00:17 GMT
> Sorry, I guess I'm a bit dense. I understand that
> Type.GetType("System.Drawing.Color") will give me a Type object with
> all the info about that class, but how can I use a Type object to
> actually *create an instance* of that class?
Your best bet is to use a TypeConverter.
You'll need to apply the TypeConverterAttribute to your custom classes if
you want them to work with this approach.
The following code demonstrates a few different examples.
Type[] types = new Type[] {
typeof(Int32),
typeof(Color),
typeof(DayOfWeek),
typeof(DateTime),
typeof(MyClass)
};
string[] values = new string[] {
"13",
"Red",
"Saturday",
"2005-05-05",
"abc123"
};
for(int i = 0; i < types.Length; i++) {
object o = TypeDescriptor.GetConverter(
types[i]).ConvertFrom(values[i]);
Console.WriteLine("{0}\t{1}", o.GetType(), o);
}
Nathan
Ken Overton - 31 Jan 2005 00:14 GMT
> Your best bet is to use a TypeConverter.
> You'll need to apply the TypeConverterAttribute to your custom classes if
> you want them to work with this approach.
Thank you, Nathan, that looks like it's exactly what I was missing.
Cheers,
-- kov