Ran into a strange erratic problem today related to Reflection/types or propertyinfo etc. I had a piece of code that is supposed to create an instance of an object if that object is not in existence. I have the information of which object has to be created. Let me give you a snap shot of the code first ..
private object CreateObjectInstance(string cmdName)
{
object instance = null;
try
{
Type type = GetObjectType(cmdName); // this will return the object type to be created
instance = type.Assembly.CreateInstance(type.FullName);
foreach (PropertyInfo property in type.GetProperties())
{
foreach (object attribute in
property.GetCustomAttributes(typeof(MyCustomAttributeType), true))
{
// Check to see if the property we are dealing with currently
// is supposed to be displayed.
MyCustomAttributeType attrib = attribute as MyCustomAttributeType;
if (attrib != null)
{
object value = null;
if (string.IsNullOrEmpty(attrib.Default)) // The attribue has a property called
// Default which returns a string
{
value = property.GetValue(instance, null);
}
else
{
value = attrib.Default;
}
// if the object that was created had an integer type get/set property
// I'm trying to do type conversions first
// Do type conversions
if (property.PropertyType == typeof(int)) // this is the problem spot
{
int result;
if (int.TryParse(attrib.Default, out result))
{
value = result;
}
}
// found one to be displayed.set default value
property.SetValue(instance, value, null);
}
}
}
}
catch (Exception exc)
{
//blah blah
}
Now the problem is on some systems (running XP SP2 with .Net framework 2.0 SP1), the line where I have shown the problem spot above, the typeOf() returns a type of Int32 as expected, but the equality operator fails and returns a false. This causes the SetValue method with a string type parameter being sent for an integer type setter property, causing exception (InValidArgumentException). Point of interest is the code does not generate an exception on systems running XP SP2 with .Net framework 2.0 SP2. However, if I change the problemetic line of code to something like this :
if (property.PropertyType == typeof(System.Int32)) // this was the problem spot
{
// blah blah
}
The problem goes away. Since the int and Int32 types are actually the same in .Net, ideally this should never have happened. But the more problemetic thing is it generates exception on one machine and not on he other running a later version of service pack. I checked the versions of System.dll assembly file on both machines. For SP1 it's 2.0.50727.1433. For framework SP2 it's 2.0.50727.3053. I really fail to understand why would this happen.
Monday, March 30, 2009
int and System.Int32 types in .Net
Stumble
del.icio.us
Reddit
MyWeb!
Facebook
Google bookmark
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment
Please leave your opinion...