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....
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With