Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine if a property is a user-defined type in C#?

Tags:

c#

reflection

How do I determine if a property is a user-defined type? I tried to use IsClass as shown below but its value was true for String properties (and who knows what else).

foreach (var property in type.GetProperties()) {
    if (property.PropertyType.IsClass) {
        // do something with property
    }
}

* Updated for more clarity *

I am trying to traverse a given type's definition and if the given type or any of its public properties are defined within the assembly, I am searching for an embedded JavaScript document. I just don't want to waste processing resources and time on native .NET types.

like image 713
Bill Heitstuman Avatar asked May 21 '14 21:05

Bill Heitstuman


1 Answers

@Bobson made a really good point:

"...Unlike some other languages, C# does not make any actual distinction between "user-defined" and "standard" types."

Technically, @Bobson gave the answer; there is no distinguishing difference between a user-defined type and one defined in the .NET Framework or any other assembly for that matter.

However, I found a couple useful ways to determine if a type is user-defined.

To search for all types defined within the given type's assembly, this works great:

foreach (var property in type.GetProperties()) {
    if (property.PropertyType.IsClass 
    && property.PropertyType.Assembly.FullName == type.Assembly.FullName) {
        // do something with property
    }
}

If the types can be defined in various assemblies, excluding the System namespace works in most cases:

foreach (var property in type.GetProperties()) {
    if (property.PropertyType.IsClass 
    && !property.PropertyType.FullName.StartsWith("System.")) {
        // do something with property
    }
}
like image 105
Bill Heitstuman Avatar answered Sep 23 '22 04:09

Bill Heitstuman