In relation to Casting generic type "as T" whilst enforcing the type of T
And with the following example
private static T deserialize<T>(string streng) where T : class
{
XmlSerializer ser = new XmlSerializer(typeof(T));
StringReader reader = new StringReader(streng);
return ser.Deserialize(reader) as T;
}
and
private static T deserialize<T>(string streng)
{
XmlSerializer ser = new XmlSerializer(typeof(T));
StringReader reader = new StringReader(streng);
return (T)ser.Deserialize(reader);
}
I'm used to doing the object as Type
casting, so I was a little confused when I found that I couldn't just do that with T
. Then I found the question above and in that a solution to the as T
compiler error.
But why is where T : class
necessary when using object as T
and not when using (T)object
?
What is the actual difference between the two ways of casting the object?
The Java compiler won't let you cast a generic type across its type parameters because the target type, in general, is neither a subtype nor a supertype.
Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind of Object, and the process of conversion from one type to another is called Type Casting.
Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion. In Java, we can cast both reference and primitive data types. By using casting, data can not be changed but only the data type is changed.
The question mark ( ? ) wildcard character can be used to represent an unknown type using generic code. Wildcards can be used with parameters, fields, local variables, and return types.
Because as
implies the cast could fail and return null. Without a : class
, T
could be int
etc - which can't be null
. With (T)obj
it will simply explode in a shower of sparks; no need to handle a null
.
As an aside (re struct
), note you can use as
if it is known you are casting to a Nullable<>
- for example:
static T? Cast<T>(object obj) where T : struct
{
return obj as T?;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With