I’m currently trying to get the type that an object was casted as in a later part of my application. This is primarily for a crazy situation that came up that would be a whole lot cleaner if I can get this to work. I wrote the following unit test that hopefully explains what I’m hoping to get working.
using System;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
namespace Test.Helper
{
[TestFixture]
public class CastingTests
{
public interface IStub { }
public class Stub : IStub { }
protected static Type GetCast(object sample)
{
//TODO work on getting method to return casted type
throw new NotImplementedException();
}
[Test]
public void GettingCastReturnsCastedType()
{
IStub stub = new Stub();
Type type = GetCast(stub);
Assert.That(type, Is.EqualTo(typeof(IStub)));
}
}
}
Pretty much I need to find a way to get the IStub type from the sample object dynamically. In the application it could be whatever the object was casted as when it was passed in. I have no idea if this is even possible, but would be pretty cool if it is. Thanks for your help in advance!
Casting an object does not have any actual effects on that object, with the possible exception of if that class were to define an explicit conversion that had performed an operation on the original value that produced a side effect…a truly obscure and unintuitive situation.
As for a general solution, no, there is no way to determine what it was “before”, because it is still the same object, just viewed from the code’s perspective as a different type. The instance itself is the same.