Click here to Skip to main content
15,346,160 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i work on csharp issue but i don't know how to solve it

i have two classes A AND B

how to instaniate it as below

A a =new A();

A B =new B();


What I have tried:

i don't know how to make it can you help me
Posted
Updated 23-Apr-22 19:46pm

1 solution

C#
A a = new A();
A B = new B();
If that code is correct, then class B has to be derived from (or inherit) class A:
C#
public class A {...}
Public class B : A {...}
Then, a variable containing an instance of A can also contain an instance of B because B "is an" A with added features.

It's like cars: a Car could be a Ford, or a Mercedes, or a BMW - but not an Orange because you can't drive an orange!
Ford, Mercedes, and BMW are all types of Car, so in a computer representation, their classes would inherit from the Car base class:
C#
public class Car {...}
Public class Ford : Car {...}
public class Mercedes : Car {...}
Public class BMW : Car {...}


Unless a class contains the variable type in it's inheritance heirarchy, you can't assign an instance of that class to it.

Make sense?
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900