Reputation: 75
I'm running the following code:
public class CfgObject
{
protected object _inst;
public CfgObject(object inst) { _inst = inst; }
}
public class CfgService : CfgObject
{
public object GetObject() { return _inst; }
public CfgService(object inst) : base(inst) {}
}
...
CfgObject obj1 = new CfgObject((object)1);
CfgService service = (CfgService)obj1;
service.GetObject();
...
I always receive
System.InvalidCastException (Unable to cast object of type 'CfgObject' to type 'CfgService')
What is the correct way of doing?
Upvotes: 0
Views: 198
Reputation: 855
You cannot cast from CfgObject
to CfgService
, only from CfgService
to CfgObject
.
Casting is always done from derived to base class.
Upvotes: 2
Reputation: 18155
If you really want an instance of CfgService
you need to create an instance of CfgService
. If you create a supertype (base) you cannot cast it to a subtype. You could do the following, although it would be rather pointless because you might as well just declare obj1
as a CfgService
.
CfgObject obj1 = new CfgService((object)1);
CfgService service = (CfgService)obj1;
service.GetObject();
Upvotes: 0