Addison Montgomery
Addison Montgomery

Reputation: 351

Check if a string can be converted to another type (C#)

I'm doing some testing things in C#, and I now need to know something. I create a class, like that:

class DChanger
{
    //Just ignore this:
    private string section = Csuc.CPanel.CPanelSection.Appearance;
    //Then the constructor: DChanger dchange = new DChanger(Internet);
    public void DChanger(string subsection)
    {
        //Code
    }
}

So, now. I want to check if "subsection" can be converted to another type. In example, i'd had an enum:

enum Subsections { Internet, Programming };

And I want to check if "subsection" is "Internet" or "Programming" (in this example, because the real enum has got a lot of more sections). Could I do that? Thankyou!

Upvotes: 4

Views: 164

Answers (2)

Hassan Boutougha
Hassan Boutougha

Reputation: 3919

to test quick it is better to test with Enum class it:

public void DChanger(string subsection)
    {
       bool b = Enum.GetNames(typeof(Subsections)).Contains(subsection);
    }

Upvotes: 1

lfboulanger
lfboulanger

Reputation: 2250

You can use Enum.Parse and watch for an exception of type ArgumentException. You can also use Enum.TryParse.

More info here http://msdn.microsoft.com/en-us/library/essfb559.aspx

Upvotes: 10

Related Questions