Jon Tackabury
Jon Tackabury

Reputation: 49237

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"?

Upvotes: 7

Views: 998

Answers (7)

ChrisLively
ChrisLively

Reputation: 88044

Create a helper function to put your test in.

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);
}

Upvotes: 1

Chris Doggett
Chris Doggett

Reputation: 20747

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

Upvotes: 1

Jason
Jason

Reputation: 28590

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;
}

Upvotes: 27

Jon Skeet
Jon Skeet

Reputation: 1499810

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

Upvotes: 12

Justin
Justin

Reputation: 86729

That looks fine to me - nice and clear.

Upvotes: 1

jjnguy
jjnguy

Reputation: 138864

I would throw it into a method to simplify it a bit:

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);
}

Upvotes: 8

Daniel A. White
Daniel A. White

Reputation: 190907

Why don't you do this?

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 might be able to get away with

obj is IComparable

Upvotes: 3

Related Questions