[c#] How to cast Object to its actual type?

If I have:

void MyMethod(Object obj) {   ...   }

How can I cast obj to what its actual type is?

This question is related to c# object types casting typeof

The answer is


In my case AutoMapper works well.

AutoMapper can map to/from dynamic objects without any explicit configuration:

public class Foo {
    public int Bar { get; set; }
    public int Baz { get; set; }
}
dynamic foo = new MyDynamicObject();
foo.Bar = 5;
foo.Baz = 6;

Mapper.Initialize(cfg => {});

var result = Mapper.Map<Foo>(foo);
result.Bar.ShouldEqual(5);
result.Baz.ShouldEqual(6);

dynamic foo2 = Mapper.Map<MyDynamicObject>(result);
foo2.Bar.ShouldEqual(5);
foo2.Baz.ShouldEqual(6);

Similarly you can map straight from dictionaries to objects, AutoMapper will line up the keys with property names.

more info https://github.com/AutoMapper/AutoMapper/wiki/Dynamic-and-ExpandoObject-Mapping


Casting to actual type is easy:

void MyMethod(Object obj) {
    ActualType actualyType = (ActualType)obj;
}

If multiple types are possible, the method itself does not know the type to cast, but the caller does, you might use something like this:

void TheObliviousHelperMethod<T>(object obj) {
    (T)obj.ThatClassMethodYouWantedToInvoke();
}

// Meanwhile, where the method is called:
TheObliviousHelperMethod<ActualType>(obj);

Restrictions on the type could be added using the where keyword after the parentheses.


This method might not be the most efficient but is simple and does the job.

It performs two operations: firstly it calls .ToString() which is basiclly a serialization, and then the deserialization using Newtonsoft nuget (which you must install).

public T Format<T>(Object obj) =>
    JsonConvert.DeserializeObject<T>(obj.ToString());

Cast it to its real type if you now the type for example it is oriented from class named abc. You can call your function in this way :

(abc)(obj)).MyFunction();

if you don't know the function it can be done in a different way. Not easy always. But you can find it in some way by it's signature. If this is your case, you should let us know.


Implement an interface to call your function in your method
interface IMyInterface
{
 void MyinterfaceMethod();
}

IMyInterface MyObj = obj as IMyInterface;
if ( MyObj != null)
{
MyMethod(IMyInterface MyObj );
}

If your MyFunction() method is defined only in one class (and its descendants), try

void MyMethod(Object obj) 
{
    var o = obj as MyClass;
    if (o != null)
        o.MyFunction();
}

If you have a large number in unrelated classes defining the function you want to call, you should define an interface and make your classes define that interface:

interface IMyInterface
{
    void MyFunction();
}

void MyMethod(Object obj) 
{
    var o = obj as IMyInterface;
    if (o != null)
        o.MyFunction();
}

How about JsonConvert.DeserializeObject(object.ToString());


I don't think you can (not without reflection), you should provide a type to your function as well:

void MyMethod(Object obj, Type t)
{
    var convertedObject = Convert.ChangeType(obj, t);
    ...
}

UPD:

This may work for you:

void MyMethod(Object obj)
{
    if (obj is A)
    {
        A a = obj as A;
        ...
    } 
    else if (obj is B)
    {
        B b = obj as B;
        ...
    }
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to types

Cannot invoke an expression whose type lacks a call signature How to declare a Fixed length Array in TypeScript Typescript input onchange event.target.value Error: Cannot invoke an expression whose type lacks a call signature Class constructor type in typescript? What is dtype('O'), in pandas? YAML equivalent of array of objects in JSON Converting std::__cxx11::string to std::string Append a tuple to a list - what's the difference between two ways? How to check if type is Boolean

Examples related to casting

Subtracting 1 day from a timestamp date Cast object to interface in TypeScript TypeScript enum to object array Casting a number to a string in TypeScript Hive cast string to date dd-MM-yyyy Casting int to bool in C/C++ Swift double to string No function matches the given name and argument types C convert floating point to int PostgreSQL : cast string to date DD/MM/YYYY

Examples related to typeof

Get class name of object as string in Swift Why does typeof array with objects return "object" and not "array"? Get type of all variables How to cast Object to its actual type? typeof operator in C When and where to use GetType() or typeof()? How do I get the type of a variable? How to efficiently check if variable is Array or Object (in NodeJS & V8)? Better way to get type of a Javascript variable? C# switch on type