Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Casting an Object using a "Type" Object in C#

This one has proven to be a little tricky for me so far. I am wondering if it is possible to type cast an object using a System.Type object.

I have illustrated below what I mean:

public interface IDataAdapter
{
    object Transform(object input);
    Type GetOutputType();
}

public class SomeRandomAdapter : IDataAdapter
{
    public object Transform(object input)
    {
        string output;

        // Do some stuff to transform input to output...

        return output;
    }

    public Type GetOutputType()
    {
        return typeof(string);
    }
}

// Later when using the above methods I would like to be able to go...
var output = t.Transform(input) as t.GetOutputType();

The above is a generic interface which is why I am using "object" for the types.

like image 887
Ryall Avatar asked Sep 03 '09 16:09

Ryall


1 Answers

The typical way to do that is to use generics, like so:

public T2 Transform<T, T2>(T input)
{
    T2 output;

    // Do some stuff to transform input to output...

    return output;
}

int    number = 0;
string numberString = t.Transform<int, string>(number);

As you mentioned in your comment below, generics are very similar to C++ Templates. You can find the MSDN documentation for Generics here, and the article "Differences Between C++ Templates and C# Generics (C# Programming Guide)" will probably be helpful.

Finally, I might be misunderstanding what you want to do inside the method body: I'm not sure how you'll transform an arbitrary type T into another arbitrary type T2, unless you specify constraints on the generic types. For example, you might need to specify that they both have to implement some interface. Constraints on Type Parameters (C# Programming Guide) describes how to do this in C#.

Edit: Given your revised question, I think this answer from Marco M. is correct (that is, I think you should use the Converter delegate where you're currently trying to use your IDataAdapter interface.)

like image 162
Jeff Sternal Avatar answered Oct 04 '22 15:10

Jeff Sternal