Rajesh Nagda
Rajesh Nagda

Reputation: 131

How to know whether the type of the attribute of a class is custom

I have a class defined like this:

public class Company
{
  public Int32 OrganisationID {get;set;}
  public CompanyStatus OrganisationStatus {get;set;} 
  // note that CompanyStatus is my custom type
}

Then I compile the code into Entity.dll. When I use the below code, I get ((System.Reflection.MemberInfo)(properties[1])).Name as CompanyStatus. How can I tell if it is a custom type or not, as I am reading all the properties dynamically?

Assembly objAssembly = Assembly.LoadFrom(@"Entities.dll");

var types1 = objAssembly.GetTypes();

foreach (Type type in types1)
{
    string name = type.Name;
    var properties = type.GetProperties(); // public properties
    foreach (PropertyInfo objprop in properties)
    {
        // Code here
    }
}

Upvotes: 2

Views: 82

Answers (1)

D Stanley
D Stanley

Reputation: 152491

Use the IsPrimitive property to tell if a property's type is not a primitive type or a string

if(objprop.PropertyType.IsPrimitive || objprop.PropertyType == typreof(string))

From MSDN:

The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single.

You may also need to check for arrays of primitive types, etc. To see if the type wraps another type use:

if(objprop.PropertyType.HasElementType)
    var t2 = objprop.PropertyType.GetElementType();

Upvotes: 4

Related Questions