Alternative Title: Dynamically convert to a type at runtime.
I want to to convert an Object to a type that will be assigned at runtime.
For example, assume that I have a function that assigns a string value(from a TextBox or Dropdownlist
) to an Object.Property
.
How would I convert the value to proper type? For instance, it could be an integer, string, or enum.
Public void Foo(object obj,string propertyName,object value)
{
//Getting type of the property og object.
Type t= obj.GetType().GetProperty(propName).PropertyType;
//Now Setting the property to the value .
//But it raise an error,because sometimes type is int and value is "2"
//or type is enum (e.a: Gender.Male) and value is "Male"
//Suppose that always the cast is valid("2" can be converted to int 2)
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}
Foo
method? – Pazice