Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

types

enums

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!

like image 386
Addison Montgomery Avatar asked Dec 21 '22 17:12

Addison Montgomery


2 Answers

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

like image 74
lfboulanger Avatar answered Dec 23 '22 05:12

lfboulanger


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);
    }
like image 22
Hassan Boutougha Avatar answered Dec 23 '22 07:12

Hassan Boutougha