5

Is there a function or by using reflection a way to get all the System types.

Like those: - System.Int64

  • System.Byte[]

  • System.Boolean

  • System.String

  • System.Decimal

  • System.Double

  • ...

We have an old enum that stores some datatype. We need to convert those to .net types.

billybob
  • 2,859
  • 6
  • 35
  • 55
  • A similar entry answering your question http://stackoverflow.com/questions/79693/getting-all-types-in-a-namespace-via-reflection Hope it helps. – Fernando Soteras Apr 09 '15 at 17:48

2 Answers2

10

Assuming you only want types from mscorlib, it's easy:

var mscorlib = typeof(string).Assembly;
var types = mscorlib.GetTypes()
                    .Where(t => t.Namespace == "System");

However, that won't return byte[], as that's an array type. It also won't return types in different assemblies. If you have multiple assemblies you're interested in, you could use:

var assemblies = ...;
var types = assemblies.SelectMany(a => a.GetTypes())
                      .Where(t => t.Namespace == "System");
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • This returns more than what I wants. Is there a way to get only the basic once like. In fact, I'm doing a mapping between the database type and the .net types. So I need to convert an old sql column in the database by replacing the it with a .net type. – billybob Apr 09 '15 at 17:52
  • 2
    @billybob: Well then you should have specified exactly what you wanted. I've answered the question you asked: "Get all .net available type in system namespace" - it's really not at all clear what you really want, but it sounds like it's *not* what you actually asked for... – Jon Skeet Apr 09 '15 at 17:53
  • Thanks. I think i will just hard code the ones that I need to map with the .net type. It answers the question. – billybob Apr 09 '15 at 17:55
2

@jon-skeet: Thanks a lot for your great solution!

If some complete noob (like me) reads this topic, I found a tiny tweak for Jon Skeet's code to get more specified output. For example:

        Assembly mscorlib = typeof(int).Assembly; 
        IEnumerable<System.Type> types = mscorlib.GetTypes()
                            .Where(t => t.Namespace == "System" && t.IsPrimitive);

The second argument "...&& t.{here_is_property}" in the last codeline is one of Type Class properties. You can try another one from .NET official reference to get what you exactly need.