4/29/2008 3:41:00 PM
In performing a little utility function today I was using the System.Reflection namespace to put together a quick working sample. Some people really take issue with utilizing this namespace but if your properties, attributes, columns, etc.. are consistently named it can save a lot of time.
So imagine a class with some public properties and an XML file with attributes matching the names of these properties. You want to select the appropriate XML (XmlTextReader, XPath, etc...) and create an instance of this class with said attribute values. For the most part the properties of this class are all of type string. Easy, I'll just use Convert.ChangeType and set accordingly. If you aren't familiar with this method, it simply returns an object of a specified type with the equivalent value.
object
a = Convert.ChangeType(1, typeof (int)); // returns 1
object b = Convert.ChangeType(1.5556, typeof (int)); // returns 2
object c = Convert.ChangeType("1", typeof (decimal)); // returns 1
One of the properties happens to now be a Guid. I was hoping this would still work.
Convert
.ChangeType("2f984574-ed9a-43b5-ade6-087325cae3cb", typeof(Guid));
Nope. InvalidCastException. Take the following piece of code. Pseudo-code alert.
foreach
(PropertyInfo property in foo.GetType().GetProperties())
{
object value = reader.GetAttribute(property.Name);
Type type = property.PropertyType;
property.SetValue(foo, Convert.ChangeType(value, type), null);
}
I would one-line this but am doing you a favor as it would wrap and become borderline unreadable (note: start looking at CSS layouts that are conducive to writing long code). So it's been established that code won't work (as far as Guids & Nullable types are concerned). In my case I created the following. Again, it's broken out into several lines for subscriber readability but can easily be limited to 1-line (I did).
foreach
(PropertyInfo property in foo.GetType().GetProperties())
{
Type type = property.PropertyType;
object value = reader.GetAttribute(property.Name);
if (type == typeof(Guid))
property.SetValue(foo, new Guid(value.ToString()), null);
else
property.SetValue(foo, Convert.ChangeType(value, type), null);
}
It may look kind of ugly but it works. I'll be exploring this in my spare time over the next couple of days (along with Type.IsGenericType) and see if I can't come up with a nice solution. 8^)
C#
