1

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,

2
  • Why do you have several similar enumerations? Is the string in the configuration always exactly the name of the enum value like in your example? Commented Jan 23, 2012 at 17:03
  • In fact they aren't mine. These types are coming from several web service references. Commented Jan 23, 2012 at 21:50

1 Answer 1

4

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
    { ... }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.