I have a class that stores a serialized value and a type. I want to have a property/method returning the value already casted:
public String Value { get; set; }
public Type TheType { get; set; }
public typeof(TheType) CastedValue { get { return Convert.ChangeType(Value, typeof(_Type)); }
Is this possible in C#?
It's possible if the class containing the property is generic, and you declare the property using the generic parameter:
class Foo<TValue> {
public string Value { get; set; }
public TValue TypedValue {
get {
return (TValue)Convert.ChangeType(Value, typeof(TValue));
}
}
}
An alternative would be to use a generic method instead:
class Foo {
public string Value { get; set; }
public Type TheType { get; set; }
public T CastValue<T>() {
return (T)Convert.ChangeType(Value, typeof(T));
}
}
You can also use the System.ComponentModel.TypeConverter
classes to convert, since they allow a class to define it's own converter.
Edit: note that when calling the generic method, you must specify the generic type parameter, since the compiler has no way to infer it:
Foo foo = new Foo();
foo.Value = "100";
foo.Type = typeof(int);
int c = foo.CastValue<int>();
You have to know the type at compile time. If you don't know the type at compile time then you must be storing it in an object
, in which case you can add the following property to the Foo
class:
public object ConvertedValue {
get {
return Convert.ChangeType(Value, Type);
}
}