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())
{
/
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.
System.TypeCode is the closest thing I can think of.
foreach(TypeCode t in Enum.GetValues(typeof(TypeCode)))
{
// do something interesting with the value...
}
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.