I have a method with an IEnumerable<T>
parameter.
T
can be one of the built-in .NET types like int
or string
or a custom class like this:
class MyClass
{
public string Foo{ get; set; }
public int Bar{ get; set; }
}
How can I recognize programmatically if T
is one of the built-in types?
I know that I can do something like this:
switch (typeof(T).Name.ToLower())
{
case "int":
case "string":
case "...": // and so on...
Console.WriteLine("It's a built-in type!");
break;
default:
Console.WriteLine("It's a custom class!");
break;
}
...but there must be a shorter/simpler way, right?
EDIT:
Okay guys, thank you very much for the answers so far.
But I'm still not sure which one is the best for my situation.
What I actually want to do is this:
I'm writing a library to convert IEnumerable<T>s
into ADODB.Recordsets
.
At the beginning of each conversion, I need to create an empty Recordset and add fields to it.
If T
is a custom class, I have to loop through its properties and create a field in the Recordset for each property of T
(with the property's name and type).
But looping through the properties only works properly if T
is a custom class.
For example, it T
is a string
, I get the properties of the string
(Chars
and Length
), which are of no use for me in this case.
This means that only checking if it's a primitive type is not enough - I need to recognize things like DateTime
and GUID
as well, and there are probably even more.
(I have to admit, I didn't notice that DateTime
is not in the list of built-in types).
So I guess what I actually want is:
Tell if T
has user-defined properties which I can loop, or not.
(no matter if it has no properties at all like int
, or properties which I don't care about like string
has)
Does this make sense?
However, I'm still not sure which answer to pick.
driis' and Jon Skeet's answer both mean that I basically have to list a lot of types (more in Jon's answer than driis' answer).
At the moment, I tend to pick Ron Sijm's answer (even though people apparently liked the other answers more), because I guess simply checking "System."
is the shortest way to do what I want, even if it does not look, well, that elegant...