Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unbox a C# object to dynamic type

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.

like image 584
McGarnagle Avatar asked Apr 10 '12 18:04

McGarnagle


People also ask

How do I start my AC for the first time?

For most central air systems, the process is simple. Simply move the switch on your thermostat from “Heat” to “Cool”. If your system was off entirely, you may need to move the switch from “Off” to “Cool” instead. Once you turn your system on, be sure to close any open windows to conserve energy.

Can I install new AC myself?

Simply put, no, you cannot replace your AC unit yourself. Even if you have the technical know-how to install an AC unit, all of the electrical components add an elevated level of risk to the process. Plus, it takes nuanced HVAC experience to ensure you get the right unit for the size of your house.


1 Answers

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...)

like image 178
Jon Skeet Avatar answered Oct 12 '22 14:10

Jon Skeet