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
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
}
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))) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With