Enum & Switch Enclosure

Hi I am using enumerations converted to a string using a switch, but this does not work. It gives a compilation error: cannot implicitly convert the type 'userControl_commontop.UserType' to 'string'

Code:

private void CommonTopChangesnew(string usertype)
{

    switch (usertype.Trim().ToUpper())
    {
        case UserType.NORMAL :
            hlkSAD.Enabled = false;
            hlkMRTQuery.Enabled = false;
            hlkReqViewer.Enabled = false;
            hlkSendnotif.Enabled = false;
            break;
        case UserType.POWER :
            hlkSAD.Enabled = false;
            hlkReqViewer.Enabled = false;
            hlkSendnotif.Enabled = false;
            break;
    }
}

enum UserType
{
    NORMAL,
    POWER,
    ADMINISTRATOR
}
+3
source share
6 answers

You can convert the userType parameter to enum using this function:

object Enum.Parse(System.Type enumType, string value, bool ignoreCase);

as

UserType utEnum =  Enum.Parse(UserType, userType, true);

and then you can invoke the switch statement as:

switch (utEnum)
    { ... }
+3
source

An enumeration is not a string, but a constant const int MY_VALUE = 1;is a string.

You should change your line to Enum:

switch ((UserType)Enum.Parse(usertype, typeof(UserType))) {
  ...
}
+5
source

:

enum UserType
{
  NORMAL,
  POWER,
  ADMINISTRATOR
}

private void CommonTopChangesnew(string usertype)
{
  switch ((UserType)Enum.Parse(typeof(UserType), usertype, true))
  {
    case UserType.NORMAL:
      hlkSAD.Enabled = false;
      hlkMRTQuery.Enabled = false;
      hlkReqViewer.Enabled = false;
      hlkSendnotif.Enabled = false;
      break;
    case UserType.POWER:
      hlkSAD.Enabled = false;
      hlkReqViewer.Enabled = false;
      hlkSendnotif.Enabled = false;
      break;
  }
}
+5

, , Enum. .

:

private void CommonTopChangesnew(UserType usertype)
{

  switch (usertype)
  {
    case UserType.NORMAL :
      hlkSAD.Enabled = false;
      hlkMRTQuery.Enabled = false;
      hlkReqViewer.Enabled = false;
      hlkSendnotif.Enabled = false;
      break;
    case UserType.POWER :
      hlkSAD.Enabled = false;
      hlkReqViewer.Enabled = false;
      hlkSendnotif.Enabled = false;
      break;
  }
}
+1

String Enum.

You must pass Enum to your method.

0
source

Option 1: Change your CommonTopChangesnew to accept a UserType enumeration as a parameter

or

Option 2: Use Enum.Parse to convert your string to a UserType enumeration in the switch block:

(UserType) Enum.Parse (typeof (UserType), user type)

0
source

Source: https://habr.com/ru/post/1707924/


All Articles