Reputation: 7923
I want to be able to see if an object is of a base type (char, int, var, string (is this a base type in C#?)). The reason for this is because I want to create a parser, which gets the fields of the object and if it comes across an object it cannot get a value out of (if it was another object inside), it will recursively get the fields out of there too. So for instance:
for (int x = 0; x < elements.Length; x++)
{
FieldInfo currenField = fields[x];
if (currenField is object) //This doesn't work because its of type "FieldInfo"
{
//pass in the current object into the function
}
else
{
elements[x] = new XElement(currenField.Name, currenField.GetValue(obj).ToString());
}
unfortunately I cannot seem to find anything online this will allow you to easily figure out if its a base type. The following is not possible either:
currenField.GetType is typeof(object)
TLDR; I cannot determine if something is a base type or not, nor can I compare types to produce the same effect
Any help is greatly appreciated!
Upvotes: 0
Views: 278
Reputation: 54638
Usually IsPrimitive
is enough, but if you need more information, I'd recommend Type.GetTypeCode().
var typeCode = Type.GetTypeCode(currenField.GetType());
switch (typeCode)
{
case TypeCode.Boolean:
break;
case TypeCode.Byte:
break;
case TypeCode.Char:
break;
case TypeCode.DBNull:
break;
case TypeCode.DateTime:
break;
case TypeCode.Decimal:
break;
case TypeCode.Double:
break;
case TypeCode.Empty:
break;
case TypeCode.Int16:
break;
case TypeCode.Int32:
break;
case TypeCode.Int64:
break;
case TypeCode.Object:
break;
case TypeCode.SByte:
break;
case TypeCode.Single:
break;
case TypeCode.String:
break;
case TypeCode.UInt16:
break;
case TypeCode.UInt32:
break;
case TypeCode.UInt64:
break;
default:
break;
}
Upvotes: 0
Reputation: 245439
What you are referring to as "basic types" are actually considered Primitive Types. You can determine if a type is a Primitive Type by using the IsPrimitive
property:
var type = currenField.GetType();
if(type.IsPrimitive)
// Primitive type
else
// Other type
Upvotes: 4