Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Switch case with Equals method in C#

Tags:

c#

asp.net

Is there a way to convert the below if else condition into Switch in C#. I am using Equals method for checking the type, but unable to convert to switch case.

if (fi.FieldType.Equals(typeof(int)))
{
    fi.SetValue(data, BitConverter.ToInt32(buffer, 0));
}
else if (fi.FieldType.Equals(typeof(bool)))
{
    fi.SetValue(data, BitConverter.ToBoolean(buffer, 0));
}
else if (fi.FieldType.Equals(typeof(string)))
{
    byte[] tmp = new byte[la.length];
    Array.Copy(buffer, tmp, tmp.Length);
    fi.SetValue(data, System.Text.Encoding.UTF8.GetString(tmp));
}
else if (fi.FieldType.Equals(typeof(double)))
{
    fi.SetValue(data, BitConverter.ToDouble(buffer, 0));
}
else if (fi.FieldType.Equals(typeof(short)))
{
    fi.SetValue(data, BitConverter.ToInt16(buffer, 0));
}

Please help us....

like image 332
Bhrathi Avatar asked Apr 18 '18 12:04

Bhrathi


People also ask

What is the use of switch case in C?

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

Can we use expression in switch case?

The expression in the switch can be a variable or an expression - but it must be an integer or a character. You can have any number of cases however there should not be any duplicates. Switch statements can also be nested within each other. The optional default case is executed when none of the cases above match.


1 Answers

With C# 7 pattern matching you can do this:

switch (fi.FieldType)
{
    case var _ when fi.FieldType.Equals(typeof(int)):
        fi.SetValue(data, BitConverter.ToInt32(buffer, 0));
        break;
    case var _ when fi.FieldType.Equals(typeof(bool)):
        fi.SetValue(data, BitConverter.ToBoolean(buffer, 0));
        break;

    //etc
}

Note that this is using _ to discard the value as we don't care about it.

like image 103
DavidG Avatar answered Nov 12 '22 04:11

DavidG