Search code examples
c#.netreflectiontypes

How to determine if a object type is a built in system type


I am writing a simple List<t> to CSV converter. My converter checks the all the t's in List and grabs all public properties and places them into the CSV.

My code works great (as intended) when you will use a simple class with a few properties.

I would like to get the List<t> to CSV converter to also accept the System types such as String and Integer. With these system types I do not want to get their public properties (such as Length, Chars etc). Thus I would like to check if the object is a System type. By System type I mean one of the built in .Net types such as string, int32, double etc.

Using GetType() I can find out the following:

string myName = "Joe Doe";

bool isPrimitive = myName.GetType().IsPrimitive; // False
bool isSealed = myName.GetType().IsSealed; // True 
// From memory all of the System types are sealed.
bool isValueType = myName.GetType().IsValueType; // False

// LinqPad users: isPrimitive.Dump();isSealed.Dump();isValueType.Dump();

How can I find if variable myName is a built in System type? (assuming we don't know its a string)


Solution

  • myName.GetType().Namespace
    This will return System if it is an in-built type.