Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting return value to a generic type

Tags:

c#

generics

Suppose we have an interface with a single generic method:

public interface IExtender
{
    T GetValue<T>(string tag);
}

and a simple implementation A of it that returns instances of two different types (B and C) depending on the "tag" parameter:

public class A : IExtender
{
    public T GetValue<T>(string tag)
    {
        if (typeof(T) == typeof(B) && tag == null)
            return (T)(object) new B();
        if (typeof(T) == typeof(C) && tag == "foo")
            return (T)(object) new C();
        return default(T);
    }
}

is it possible to avoid the double cast (T)(object)? Or, is there a way to tell the compiler "hey, I am sure that this cast won't fail at runtime, just let me do it without first casting to object!"

like image 571
fog Avatar asked Jul 19 '12 07:07

fog


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.

What is generic type in C#?

Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces.


1 Answers

public T MyMethod<T>(string tag) where T : class
    {
        return new A() as T;
    }
like image 143
Tomas Grosup Avatar answered Sep 18 '22 04:09

Tomas Grosup