views:

209

answers:

4

Hi!

How to write a simple method, that checks whether a concrete type is a custom struct (created with public struct { };) or not.

Checking Type.IsValueType is not enough, because it is also true to int, long, etc, and adding a check to !IsPrimitiveType won't exclude decimal, DateTime and maybe some other value types. I know that most of the built in value types are actually "structs", but I only want to check for "custom structs"

These questions are mostly the same but without the answer I need:

EDIT: from the answers mentioned the "check for the 'System' prefix" was the most stable (although it's still a hack). I finally decided to create an Attribute that you have to decorate the struct with, in order the framework to pick it up as a custom struct. (The other choice I thought was to create an empty interface, and let the struct implement that empty interface, but the attribute way seemed more elegant)

Here is my original custom struct checker if someone if interested:

type.IsValueType && !type.IsPrimitive && !type.Namespace.StartsWith("System")
+2  A: 

Well, DateTime, decimal, etc meet your requirements. As far as the CLR is concerned, they are custom structs. A hack, but you can just check to see if the namespace starts with "System".

Matt Greer
Of course your own namespace could start with System... :) No one would do that, right?
Nelson
Yeah, which is why I called that a hack.
Matt Greer
+7  A: 

There is no difference between a struct defined in the framework, and a struct defined by yourself.

A couple of ideas could be:

  • Keep a whitelist of framework structs, and exclude those;
  • Identify the assembly (DLL) the type is defined in, and keep a whitelist of framework assemblies.
  • Identify the namespace the type lives in, and exclude the framework ones.
stusmith
In the context of the comment on using Fluent NHibernate, a whitelist of "well-known" structs would be the best approach. The list is short enough to be easily understood and is likely to never change.
Programming Hero
Agreed, as you find each one that causes a crash, add it to the whitelist (or blacklist or whatever you call it), and continue. The framework doesn't have too many structs.
stusmith
Yes, but unfortunately there are no lists for this. And if you miss something out, and use that struct later you won't know why the frameworks starts crashing
SztupY
+2  A: 

You can check if the struct type falls under anywhere within System namespace. But again that's not a reliable solution.

this. __curious_geek
A: 

putting the above comments into an extention method:

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

should work

GreyCloud