6

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....

7
  • 2
    Yes, with C# 7.0 – Pattern Matching Commented Apr 18, 2018 at 12:38
  • You can see an example of c# pattern matching here: stackoverflow.com/a/44447980/1736047 Commented Apr 18, 2018 at 12:42
  • if C# 7 the use pattern expression matching https://learn.microsoft.com/en-us/dotnet/csharp/pattern-matching Or below then convert the typeof(type) to string and match with string representation of fi.FieldType Commented Apr 18, 2018 at 12:43
  • @TimSchmelter there's no need for pattern matching, the code checks the value of FieldType. A common switch would work. Commented Apr 18, 2018 at 12:44
  • @PanagiotisKanavos But the compiler will complain that you need to use a constant value if you try to compare it with typeof(x) Commented Apr 18, 2018 at 12:46

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks for quick reply.
You could use Type.GetTypeCode and use a switch with earlier versions too
@Bhrathi this looks like reflection code. What are you really trying to do? There may be an implementation for this already
@PanagiotisKanavos Yes, that's assuming they're all CLR types of course
While this is technically using a switch, you're still using it as if it were an if else chain. fi.FieldType in switch (fi.FieldType) is unused, you could put literally any value there. You're only using the when boolean_evaluation part, which is no different from if(boolean_evaluation). This is one of those cases where you're changing the syntax to fit with the proposed change, while ignoring the actual underlying reason why the change is needed.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.