RKN
RKN

Reputation: 962

Type casting using string of type

I have fully qualified class name which I have to use for type casting. I can get type using

someType=Type.GetType("TypeName"). 

After Deserializing I am getting object which I have to typecast into particular type i.e TypeName.

I tried

obj = (someType) SXmlSerializer.Deserialize("TypeName", someData);

but that doesn't works . Is there any option available to do typecasting using only class name as string?

I have to convert it into someType because I have to modify value for property i.e. obj.SomeProperty = "AnotherValue".

Upvotes: 0

Views: 90

Answers (1)

D Stanley
D Stanley

Reputation: 152566

I have to convert it into someType because I have to modify value for property i.e. obj.SomeProperty = "AnotherValue".

But if you don't know the type at compile time, how do you know it has a SomeProperty property?

If you want to assume that it does and defer type-checking to runtime then you could use dynamic:

dynamic obj = SXmlSerializer.Deserialize("TypeName", someData);

then you can do

obj.SomeProperty = "AnotherValue";

Which will fail at runtime if the object does not have a SomeProperty property.

Casting only affects how methods are bound at compile-time. There's no value in casting if you don't know the type at compile-time.

Upvotes: 2

Related Questions