If I have:
void MyMethod(Object obj) { ... }
How can I cast obj
to what its actual type is?
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());
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;
...
}
}
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());
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.