How to determine if a .NET type is a custom structure?

How to write a simple method that checks whether a particular type is a custom structure (created using public struct { }; ) or not.

Checking Type.IsValueType not enough, as this is also true for int , long , etc. and adding a check on !IsPrimitiveType does not exclude decimal , DateTime and possibly some other value types. I know that most of the built-in value types are actually "structures", but I only want to check for "custom structures"

These questions are basically the same, but without an answer I need:

  • # one
  • # 2
  • # 3

EDIT: of the answers mentioned, β€œchecking for aβ€œ system prefix ”was the most stable (although it still breaks). Finally, I decided to create an Attribute that you need to decorate with a structure so that the structure picks it up as a custom structure. (Another choice that I I thought it was creating an empty interface, and let the structure implement this empty interface, but the attribute path seemed more elegant)

Here is my original user structure controller, if anyone is interested:

 type.IsValueType && !type.IsPrimitive && !type.Namespace.StartsWith("System") && !type.IsEnum 
+6
reflection c # types struct
source share
5 answers

Well, DateTime, decimal, etc. match your requirements. As for the CLR, they are custom structures. Hacked, but you can just check if the namespace starts with "System".

+5
source share

There is no difference between the structure defined in the structure and the structure defined by you.

A few ideas might be:

  • Keep a white list of structural structures and exclude them;
  • Define the assembly (DLL) in which the type is specified and keep a whitelist of the frame assembly.
  • Define the namespace in which the type is located and exclude it.
+8
source share

inclusion of these comments in the extension method:

 public static class ReflectionExtensions { public static bool IsCustomValueType(this Type type) { return type.IsValueType && !type.IsPrimitive && type.Namespace != null && !type.Namespace.StartsWith("System."); } } 

must work

+3
source share

You can check if the structure type falls within the system namespace . But again, this is not a reliable solution.

+2
source share

Do you have a value that comes with this type? Call the ToString method and check if the returned string begins with "{".

If you have no value, check if it has a constructor without parameters. If it is not, this is the constructor. If so, use Activator to instantiate and call the ToString method again.

-one
source share

All Articles