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.
Why make it complicated, when you are sure that it returns a string?
If I have misunderstood what you are saying, here is one more way
You are better off using something like the Converter delegate
for an example, check out msdn
This is what I have gone with (based off the IEnumerable structure):
Would it not make more sense to use an actual generic interface:
The typical way to do that is to use generics, like so:
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 typeT2
, 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 yourIDataAdapter
interface.)