Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to cast objects to a generic type

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?

like image 218
Heki Avatar asked Dec 21 '10 08:12

Heki


People also ask

Can you cast to a generic type Java?

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.

Which is used for casting of object to a type or a class?

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.

What is the purpose of casting an object to another type?

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.

Which character is used for generic type?

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.


1 Answers

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?;
}
like image 114
Marc Gravell Avatar answered Oct 12 '22 02:10

Marc Gravell