xkcd
xkcd

Reputation: 2590

Generic method returning value according to input parameter

I'm new to using generic classes. Here is my question:

I have several enumerations like: x.PlatformType, y.PlatformType, z.PlatformType etc...

public class Helper<T>
{
    public T GetPlatformType(Type type)
    {
        switch (System.Configuration.ConfigurationManager.AppSettings["Platform"])
        {
            case "DVL":
                return // if type is x.PlatformType I want to return x.PlatformType.DVL
                       // if type is y.PlatformType I want to return y.PlatformType.DVL
                       // etc
            default:
                return null;
        }
    }
}

Is it possible to develop a method like this?

Thank in advance,

Upvotes: 1

Views: 343

Answers (1)

driis
driis

Reputation: 164281

Since you know it's an Enum, the simplest thing would be to use Enum.TryParse:

public class Helper<T> where T : struct
{
    public T GetPlatformType()
    {
        string platform = System.Configuration.ConfigurationManager.AppSettings["Platform"];
        T value;
        if (Enum.TryParse(platform, out value))
            return value;
        else
            return default(T);  // or throw, or something else reasonable
    }
}

Note, I removed the Type parameter because I assumed it was given by T. Perhaps it would be better for you (depends on usage scenario) to make the method generic, and not the whole class - like this:

public class Helper 
{
    public T GetPlatformType<T>() where T : struct
    { ... }
}

Upvotes: 4

Related Questions