Get all .net available type in system namespace
Asked Answered
U

2

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.

Ungula answered 9/4, 2015 at 17:42 Comment(1)
A similar entry answering your question #80193 Hope it helps.Consummate
F
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");
Fire answered 9/4, 2015 at 17:44 Comment(3)
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.Ungula
@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...Fire
Thanks. I think i will just hard code the ones that I need to map with the .net type. It answers the question.Ungula
B
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.

Balneal answered 22/4, 2021 at 8:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.