-2

I'm trying to cast a base object into a derived object.

Like so:

DerivedClass castedBaseObject = (randomDerivedObject.GetType())originalBaseObject;

The example above does not work, throwing the following error: error CS1003: Syntax error, ',' expected

Nomnom
  • 4,193
  • 7
  • 27
  • 37
  • 1
    Can you supply a little more context as to why you want to achieve this? – Bijington Dec 14 '20 at 20:57
  • @Bijington It's long, basically I'm working with an API and trying to wrap a class around the already defined classes, when using the already defined methods, they return the base class (type), so in order for me to use the wrapper I wrote (which took me quite a bit of time) I have to cast the base object. I'm using quite a few different wrapper classes so I'd like to iterate and cast dynamically. – Nomnom Dec 14 '20 at 21:01
  • If you know nothing about the type at compile time, this is not possible with the `var` keyword, as it expects a static type. You can, however, use the `dynamic` keyword. – Xaver Dec 14 '20 at 21:03
  • For _conversion_, see answers at e.g. https://stackoverflow.com/questions/9009986/how-to-cast-an-object-to-a-type-extracted-at-runtime and https://stackoverflow.com/questions/4010144/convert-variable-to-type-only-known-at-run-time – Peter Duniho Dec 14 '20 at 21:21
  • @xaver sorry, fixed it. – Nomnom Dec 14 '20 at 21:30

1 Answers1

0

If you have a finite number of types (let's call them MyClass1, MyClass2, ..., MyClassN) and you know that your object originalBaseObject has one of these types, you could do the following:

if (originalBaseObject is MyClass1 tmp1)
{
    // do something with tmp1
}
else if (originalBaseObject is MyClass2 tmp2)
{
    // do something with tmp2
}
// ...
// and the last type
else if (originalBaseObject is MyClassN tmpN)
{
    // do something with tmpN
}
else {
    throw new Exception("Non of the given types");
}
Xaver
  • 1,035
  • 9
  • 17