Passing just a type as a parameter in C#

Mark Mayo picture Mark Mayo · Jun 8, 2012 · Viewed 188.3k times · Source

Hypothetically it'd be handy for me to do this:

foo.GetColumnValues(dm.mainColumn, int)
foo.GetColumnValues(dm.mainColumn, string)

where the GetColumns method will call a different method inside depending on the type passed.

Yes, I could do it as a boolean flag or similar, I just wondered if there was a way to perhaps pass this, and then ask:

typeof(arg[1]) or similar...

I could also override the method, use generics, etc - I know there are different ways to do this, I was just curious if this was possible.

Answer

Reed Copsey picture Reed Copsey · Jun 8, 2012

There are two common approaches. First, you can pass System.Type

object GetColumnValue(string columnName, Type type)
{
    // Here, you can check specific types, as needed:

    if (type == typeof(int)) { // ...

This would be called like: int val = (int)GetColumnValue(columnName, typeof(int));

The other option would be to use generics:

T GetColumnValue<T>(string columnName)
{
    // If you need the type, you can use typeof(T)...

This has the advantage of avoiding the boxing and providing some type safety, and would be called like: int val = GetColumnValue<int>(columnName);