Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through the built-in types in C#?

Tags:

c#

I want to iterate through the built-in types (bool, char, sbyte, byte, short, ushort, etc) in c#.

How to do that?

foreach(var x in GetBuiltInTypes())
{
//do something on x
}
like image 950
LaTeX Avatar asked Mar 05 '11 04:03

LaTeX


3 Answers

System.TypeCode is the closest thing I can think of.

foreach(TypeCode t in Enum.GetValues(typeof(TypeCode)))
{ 
    // do something interesting with the value...
}
like image 167
Sanjeevakumar Hiremath Avatar answered Oct 17 '22 01:10

Sanjeevakumar Hiremath


It depends on how you define "built-in" types of course.

You might want something like:

public static IEnumerable<Type> GetBuiltInTypes()
{
   return typeof(int).Assembly
                     .GetTypes()
                     .Where(t => t.IsPrimitive);
}

This should give you (from MSDN):

Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single.

If you have a different definition, you might want to enumerate all of the types in common BCL assemblies (such as mscorlib, System.dll, System.Core.dll etc.), applying your filter as you go along.

like image 41
Ani Avatar answered Oct 17 '22 01:10

Ani


There's no built-in way to do that; you can try:

foreach (var type in new Type[] { typeof(byte), typeof(sbyte), ... })
{
    //...
}

Of course, if you're going to be doing this a lot, factor out the array and put it inside a static readonly variable.

like image 27
user541686 Avatar answered Oct 17 '22 00:10

user541686