I wish to extend a base class in C# with some additional functionality. I have existing code which returns an array of the base class objects (Account) which I need to convert into the extended version.
So I have the extended version:
class AccountXtra : Account { public int Period { get; set; } public int Visitors { get; set; } public string ContactName { get; set; } }
All is good.
BUT how do I create a new instance of AccountXtra when I have a instance of Account?
I have tried:
//This doesn't work AccountXtra newInstance = (AccountXtra)accountInstance; //This also doesn't work AccountXtra newInstance = new AccountXtra(); newInstance = accountInstance;
You need to be generating new objects of the derived class now, not the base. Replace your old calls to
new Accountwithnew AccountXtra. Or, you need a constructor forAccountXtrathat takes anAccountobject and makes a new derived-class version of it:Explanation: You can’t cast a base class to a derived class unless it is of the derived class type. This will work:
But this will not: