Type Conversions in C Sharp
Base Class to SubClass.
public class BaseClass {}
public class SubClass : BaseClass {}
BaseClass baseObject;
- Solution 1:
is
if(baseObject is SubClass subObject)
{
// do sth using subObject.
}
- Solution 2:
as
var newSubObject = baseObject as SubClass;
PS: return null if it’s not the exact type, will not throw exception.
- Solution 3:
(Type)
var newSubObject = (SubClass)baseObject;
PS: throw exception if it’s not the exact type.