Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement simplification in C#

I have a line of code that looks like this:

if (obj is byte || obj is int || obj is long || obj is decimal || obj is double || obj is float)

Is it possible to write something more elegant than this? Something like:

if (obj is byte, int, long)

I know that my example isn't possible, but is there a way to make this look "cleaner"?

like image 550
Jon Tackabury Avatar asked Jul 28 '09 14:07

Jon Tackabury


2 Answers

You could write an extension method on object to give you syntax like:

if (obj.Is<byte, int, long>()) { ... }

Something like this (use multiple versions for fewer or more generic arguments:

public static bool Is<T1, T2, T3>(this object o)
{
    return o is T1 || o is T2 || o is T3;
}
like image 186
Jason Avatar answered Sep 25 '22 10:09

Jason


Only:

static readonly HashSet<Type> types = new HashSet<Type> 
    { typeof(byte), typeof(int), typeof(long) etc };

...

if (types.Contains(obj.GetType())
{
}

Or use obj.GetType().GetTypeCode().

like image 30
Jon Skeet Avatar answered Sep 22 '22 10:09

Jon Skeet