Using Switch case with Equals method in C #

Is there a way to convert the following else condition to Switch in C #. I use the Equals method to check the type, but cannot convert it to 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....

+4
source share
1 answer

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 used _to discard the value, since we do not care about it.

+8
source

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


All Articles