If operator 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 that? Something like:

 if (obj is byte, int, long) 

I know that my example is impossible, but is there a way to make this "cleaner"?

+7
c # if-statement
source share
7 answers

You can write an extension method on an object to give you syntax, for example:

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

Something like this (use multiple versions for more or less general arguments:

 public static bool Is<T1, T2, T3>(this object o) { return o is T1 || o is T2 || o is T3; } 
+27
source share

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

+12
source share

I would throw it into a method to simplify it:

 private static bool ObjIsNumber(object obj) { return (obj is byte || obj is int || obj is long || obj is decimal || obj is double || obj is float); } 
+8
source share

Why don't you do it?

 bool IsRequestedType(object obj) { if (obj is byte || obj is int || obj is long || obj is decimal || obj is double || obj is float) return true; return false; } 

Or you can leave with

 obj is IComparable 
+3
source share

It looks good to me - nice and clear.

+1
source share

Create a helper function to enter your test.

Something like

 public static Boolean IsNumeric(Object myObject) { return (obj is byte || obj is int || obj is long || obj is decimal || obj is double|| obj is float); } 
+1
source share
 public static bool IsOneOf(object o, params Type[] types) { foreach(Type t in types) { if(o.GetType() == t) return true; } return false; } long l = 10; double d = 10; string s = "blah"; Console.WriteLine(IsOneOf(l, typeof(long), typeof(double))); // true Console.WriteLine(IsOneOf(d, typeof(long), typeof(double))); // true Console.WriteLine(IsOneOf(s, typeof(long), typeof(double))); // false 
+1
source share

All Articles