How to iterate over built-in types in C #?

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

How to do it?

foreach(var x in GetBuiltInTypes()) { //do something on x } 
+8
c #
source share
3 answers

System.TypeCode is the closest I can think of.

 foreach(TypeCode t in Enum.GetValues(typeof(TypeCode))) { // do something interesting with the value... } 
+17
source share

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

You might need 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 may need to list all types in common BCL assemblies (e.g. mscorlib, System.dll, System.Core.dll, etc.), applying your filter as you go.

+5
source share

There is no built-in way to do this; you can try:

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

Of course, if you are going to do this a lot, drop the array and put it inside the static readonly variable.

+1
source share

All Articles