6

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

Jasper
  • 2,314
  • 3
  • 26
  • 33

2 Answers2

11

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
}
Jon
  • 428,835
  • 81
  • 738
  • 806
2

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))) { }
ispiro
  • 26,556
  • 38
  • 136
  • 291
  • 1
    Why not just `!(variable is IEnumerable)` ? – nawfal Oct 10 '13 at 09:25
  • 1
    @joe IEnumerable is the base interface for all enumerable types. An array is enumerable anyway. See http://stackoverflow.com/questions/4590366/how-to-check-if-a-variable-is-an-ienumerable-of-some-sort – nawfal Oct 10 '13 at 09:27
  • @nawfal You're correct. I was thinking of a Type, not a variable. Edited now. – ispiro Oct 10 '13 at 09:33
  • @joe You're welcome. Note that the first option in the answer you accepted will fail for any "scalar" Type you might declare, and most of the .Net "scalar" types such as `Form`. As for the second - you'd have to add checks for every Type you need to check.(This is assuming I understood you correctly - that you're looking to exclude array's, List's, etc.) – ispiro Oct 10 '13 at 09:47