I try to set a Nullable<> property dynamicly.
I Get my property ex :
PropertyInfo property = class.GetProperty(\"PropertyName\"); // My property i
Here is a complete example showing how to do it:
using System;
using System.Reflection;
class Test
{
static void Main()
{
Foo foo = new Foo();
typeof(Foo).GetProperty("Bar")
.SetValue(foo, 1234, null);
}
}
class Foo
{
public Nullable Bar { get; set; }
}
As others have mentioned you need to pass the right type to the SetValue
function but your other reflection code is not quite right either. You need to get the type of the class in question before you can query for its members.
Edit: If I understand correctly you are trying to set a string value to any property via reflection. In order to do this you will need to do some type inspection and type conversion.
Here is an example of what I mean:
using System;
using System.Reflection;
class Test
{
static void Main()
{
Foo foo = new Foo();
PropertyInfo property = typeof(Foo).GetProperty("Bar");
Object value =
Convert.ChangeType("1234",
Nullable.GetUnderlyingType(property.PropertyType)
?? property.PropertyType);
property.SetValue(foo, value, null);
}
}
class Foo
{
public Nullable Bar { get; set; }
}
This approach can be safely used regardless of whether or not the property is Nullable<>
.