How to Cast Object to Its Actual Type

How to cast Object to its actual type?

If you know the actual type, then just:

SomeType typed = (SomeType)obj;
typed.MyFunction();

If you don't know the actual type, then: not really, no. You would have to instead use one of:

  • reflection
  • implementing a well-known interface
  • dynamic

For example:

// reflection
obj.GetType().GetMethod("MyFunction").Invoke(obj, null);

// interface
IFoo foo = (IFoo)obj; // where SomeType : IFoo and IFoo declares MyFunction
foo.MyFunction();

// dynamic
dynamic d = obj;
d.MyFunction();

How to cast object to its actual type

Assuming you can change Foo, but not its signature, you could do this:

private void Foo(MyClass cl)
{
TestGeneric((dynamic)cl);
}

This will resolve the version of TestGeneric that gets called at runtime instead of at compile time, calling TestGeneric<MyClass2> when cl is of that type.

cast object with a Type variable

newObjectType is an instance of the Type class (containing metadata about the type) not the type itself.

This should work

var newObject = givenObject as MyClass;

OR

var newObject = (MyClass) givenObject;

Casting to an instance of a type really does not make sense since compile time has to know what the variable type should be while instance of a type is a runtime concept.

The only way var can work is that the type of the variable is known at compile-time.


UPDATE

Casting generally is a compile-time concept, i.e. you have to know the type at compile-time.

Type Conversion is a runtime concept.


UPDATE 2

If you need to make a call using a variable of the type and you do not know the type at compile time, you can use reflection: use Invoke method of the MethodInfo on the type instance.

object myString = "Ali";
Type type = myString.GetType();
MethodInfo methodInfo = type.GetMethods().Where(m=>m.Name == "ToUpper").First();
object invoked = methodInfo.Invoke(myString, null);
Console.WriteLine(invoked);
Console.ReadLine();

C# cast object type

try like this:

TypeA a = (TypeA)(object)t;

Cast a property to its actual type dynamically using reflection (where actual type is generic)

Change your code to receive property to:

PropertyInfo propInfo = tester.GetType().GetProperty("MyIntProperty");

So you use constructed generic type.

C# how to cast object to runtime type?

TL;DR

You can't cast something to an unknown type specified at runtime. That would mean that within your code, you don't know what the object's properties or methods are unless you use even more reflection. In that case what would be the point of casting it?


Sometimes we deal with types that aren't known until runtime. But unless the type really doesn't matter at all, the object is useless unless we can cast it to some predetermined type that is specified in our code, not at runtime.

In this line of code:

var val = property.GetValue(obj); 

the declared type of val is inferred by the compiler. That type is object because that's the type that GetValue returns. The actual type of the object could be string, int, List<Foo>, whatever. But you've got a variable val of type object.

If you could do this:

var val = property.GetValue(obj) as runtimeType;    

Then what would the compile-time type of val be? How can it have any, since runTimeType is a runtime value? The object is useless unless you can call methods or inspect its properties. But you can't do that without knowing the type, unless you use more reflection. But if your're going to do that then there's no point in casting it.

Somewhere downstream from the code you've posted you'll presumably want to actually do something with the object that involves its methods or properties. That means knowing what type you think it is and casting it as that type. That would be a type specified in your code, not something determined at runtime.

For example:

var val = property.GetValue(obj); // I know this is a string
var myString = (string)val;
var findX = myString.IndexOf("X");

I think it's a string so I cast it as a string. (There could be additional checks in there.) Now that I've cast it, I've got a variable that's declared as type string, and I can use it as a string. (Unless it wasn't a string - then it will throw a runtime exception.)

That's the benefit of casting - it allows us to assign something to a strongly-typed variable with a type we specify and then use it accordingly. Casting to an unknown type wouldn't benefit us.


At the risk of adding confusion: Someone could say that generics represent types unspecified at runtime, but that's not exactly true. List<T> doesn't specify what T is, but if you create a List<T>, somehow, somewhere you're going to specify the type in your code. In the vast majority of normal scenarios we have to know something about the type of an object or else the object is useless to us.

Cast a property to its actual type dynamically using reflection (where actual type is generic) v2

fsr is the SmartRowVertrag. You're trying to get the IsSearchValue from that - but it doesn't exist.

Instead, you'll need to call GetValue twice - once on prop, passing in fsr (so which is equivalent to using fsr.ID or dsr.VSNR) and then once on propInfo passing in the result of that first call.

Next, your dynamic use is trying to get IsSearchValue on the result of propInfo.GetValue() - you're trying to evaluate something.IsSearchValue.IsSearchValue, effectively.

Here's corrected code for that part:

public static object RetData3(object fsr)
{
object retVal = new object();
var props = fsr.GetType().GetProperties();
foreach (var prop in props)
{
PropertyInfo propInfo = prop.PropertyType.GetProperty("IsSearchValue");
if (propInfo != null)
{
object fieldInfo = prop.GetValue(fsr);
object isSearchValue = propInfo.GetValue(fieldInfo);
if (isSearchValue.Equals(true))
{
Console.WriteLine($"{prop.Name} has a searchable field");
}
}
}
return retVal;
}

You could avoid using reflection twice though if you had either a non-generic interface that DataFieldInfo2<T> implemented, or a base class. For example:

public interface IDataFieldInfo
{
bool IsSearchValue { get; }
}

public class DataFieldInfo2<T> : IDataFieldInfo
{
...
}

You could then make your reflection code much clearer:

public static object RetData3(object fsr)
{
var fieldProperties = fsr.GetType().GetProperties()
.Where(prop => typeof(IDataFieldInfo).IsAssignableFrom(prop.PropertyType));
foreach (var fieldProperty in fieldProperties)
{
var field = (IDataFieldInfo) fieldProperty.GetValue(fsr);
if (field.IsSearchValue)
{
Console.WriteLine($"{fieldProperty.Name} is a search value field");
}
}

// We don't actually know what you're trying to return
return null;
}

Casting an object to its original class

What you are trying to do is called a dynamic invocation. The closest thing you can do is to use reflection.

Method method = getClass().getMethod("someHandlingMethod", obj.getClass());
method.invoke(this, obj);


Related Topics



Leave a reply



Submit