Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a variable is scalar?

Tags:

c#

.net

Is there a method to check a variable is scalar type?

scalar variables are those containing an integer, float, double , string or boolean but not array object

thanks

like image 245
Jasper Avatar asked Dec 20 '22 23:12

Jasper


2 Answers

It depends on what you mean by "scalar", but Type.IsPrimitive sounds like a good match: it's true for boolean, integer types, floating point types and char.

You can use it as in

var x = /* whatever */
if (x.GetType().IsPrimitive) {
    // ...
}

For a more granular approach you can use Type.GetTypeCode instead:

switch (x.GetType().GetTypeCode()) {
    // put all TypeCodes that you consider scalars here:
    case TypeCode.Boolean:
    case TypeCode.Int16:
    case TypeCode.Int32:
    case TypeCode.Int64:
    case TypeCode.String:
        // scalar type
        break;
    default:
        // not a scalar type
}
like image 200
Jon Avatar answered Dec 31 '22 06:12

Jon


I'm not sure this will always work, but it might be enough for your needs:

if (!(YourVarHere is System.Collections.IEnumerable)) { }

Or, for checking a Type:

if(!typeof(YourTypeHere).GetInterfaces().Contains(typeof(System.Collections.IEnumerable))) { }
like image 37
ispiro Avatar answered Dec 31 '22 06:12

ispiro