Saturday, 16 September 2017

c# - Casting a variable using a Type variable



In C# can I cast a variable of type object to a variable of type T where T is defined in a Type variable?


Answer




Sure you can here is both a simple (assume this is a T-type cast) cast and if convenient a (assume we can convert this to a T) convert:



public T CastExamp1(object input) {   
return (T) input;
}

public T ConvertExamp1(object input) {
return (T) Convert.ChangeType(input, typeof(T));
}



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. The Convert.ChangeType method tries to convert any Object to the Type provided as the second argument.



For example:



Type intType = typeof(Int32);
object value1 = 1000.1;


// Variable value2 is now an int with a value of 1000
object value2a = Convert.ChangeType(value1, intType);
int value2b = Convert.ChangeType(value1, intType);

// Variable value3 is now an int with a value of 1000
dynamic value3 = Convert.ChangeType(value1, intType);


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 something to a something else without 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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...