In C# can I cast a variable of type object to a variable of type T where T is defined in a Type variable?
In C# can I cast a variable of type object to a variable of
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here is an example of a cast and a convert:
Edit:
Some people in the comments say that this answer doesn’t answer the question. But the line
(T) Convert.ChangeType(input, typeof(T))provides the solution. TheConvert.ChangeTypemethod tries to convert any Object to the Type provided as the second argument.For example:
I’ve written the answer with generics, because I think it is a very likely sign of code smell when you want to cast
a somethingtoa something elsewithout handling an actual type. With proper interfaces that shouldn’t be necessary 99.9% of the times. There are perhaps a few edge cases when it comes to reflection that it might make sense, but I would recommend to avoid those cases.Edit 2:
Few extra tips:
objectordynamicvariable.