Class A { }
Class B : A { }
B ItemB = new B();
A ItemA = (A)B;
Console.WriteLine(ItemA.GetType().FullName);
Is it possible to do something like a
For amusement, if you wanted to lose all of the derived data you could do this:
class Program
{
[DataContract(Name = "A", Namespace = "http://www.ademo.com")]
public class A { }
[DataContract(Name = "A", Namespace = "http://www.ademo.com")]
public class B : A {
[DataMember()]
public string FirstName;
}
static void Main(string[] args)
{
B itemB = new B();
itemB.FirstName = "Fred";
A itemA = (A)itemB;
Console.WriteLine(itemA.GetType().FullName);
A wipedA = WipeAllTracesOfB(itemB);
Console.WriteLine(wipedA.GetType().FullName);
}
public static A WipeAllTracesOfB(A a)
{
DataContractSerializer serializer = new DataContractSerializer(typeof(A));
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, a);
ms.Position = 0;
A wiped = (A)serializer.ReadObject(ms);
return wiped;
}
}
}
If you use the debugger you will see the FirstName is still stored in the field FirstName when it is cast to an A, when you get an A back from WipeAllTracesOfB there is no FirstName, or any trace of B.