Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a .NET Type is a custom struct? [duplicate]

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:

  • #1
  • #2
  • #3

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") && !type.IsEnum
like image 739
SztupY Avatar asked Apr 26 '10 13:04

SztupY


1 Answers

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.
like image 131
stusmith Avatar answered Oct 05 '22 23:10

stusmith