How to unbox a C# object to dynamic type
Asked Answered
M

1

11

I'm trying to do something like this:

void someMethod(TypeA object) { ... }

void someMethod(TypeB object) { ... }

object getObject()
{
    if (...) return new TypeA();
    else return new TypeB();
}

object obj = getObject();
(obj.GetType()) obj;  // won't compile
someMethod(obj);

Obviously I'm confused here. I know I could make this work by just writing out a conditional statement --

if (obj.GetType() == typeof(TypeA)) obj = (TypeA)obj;
else if (obj.GetType() == typeof(TypeB)) obj = (TypeB)obj;

-- but isn't there some way to do this at runtime?

EDIT I agree it seems like perhaps not the best design choice, so here's the context. The point of the above code is Repository base class for Mongo DB. I want it to be able to handle different kinds of tables. So, someMethod() is actually remove; and TypeA and TypeB are ObjectID and Guid; the code at the bottom is part of a type-agnostic remove method that accepts the ID as a string; and getObject() is a method to parse the ID parameter.

Mantegna answered 10/4, 2012 at 18:7 Comment(5)
You are conflating a type T with the runtime type information associated with it: typeof(T). They are not the same thing and cannot be substituted for each other.Samirasamisen
There are likely to be better design choices, but you left the actual goal of the code out of your post. Maybe we could provide you with a better and totally different way of writing the solution to your problem if you let us know what you were trying to accomplish with this code.Stereoisomer
@Kirk Woll, I know the difference, I just wanted to illustrate what I was trying to do.Mantegna
@John Fisher, added the context. I gather that would be maybe a question for "Code Review" exchange, but if you have ideas, I'd be happy to open it as a separate question.Mantegna
Have a look at Massive. You'll find a lot of good ideas there.Caryncaryo
D
20

If you're using .NET 4 and C# 4, you can use dynamic for this:

dynamic obj = GetObject();
SomeMethod(obj);

Otherwise, you'll have to use reflection to find and invoke the right method. Overload resolution (for non-dynamic types) is performed at compile-time.

(Note that unless TypeA and TypeB are structs, you wouldn't be unboxing anyway...)

Dittman answered 10/4, 2012 at 18:8 Comment(4)
@RobertHarvey: Not given the way the question's written, where it's picking overloads within the same type.Dittman
I wasn't aware that overload resolution extended to the runtime type of the dynamic object.Caryncaryo
@RobertHarvey: That's the whole point of dynamic - that effectively pretty much everything is deferred to execution time, using the actual type of the object.Dittman
@RobertHarvey: About the only thing that doesn't extend to dynamic is extension methods; those are only available at compile time.Martica

© 2022 - 2024 — McMap. All rights reserved.