Reputation: 7
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
C c = new C();
c = new B();
}
}
class B
{
}
class C : B
{
}
}
please can anyone explain this error ? i am new to coding. i want to check the properties of hiding and overriding the methods. your efforts are highly appreciated
Upvotes: 0
Views: 82
Reputation: 51430
You are trying to assign a B
to a C
, which is not correct is every case. Try to rename the objects to make it easier:
class Animal
{
}
class Dog : Animal
{
}
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog ();
dog = new Animal(); // Oops ! Not possible
}
}
A Dog
is always an Animal
, but every Animal
is not necessarily a Dog
.
The following would be correct though:
Animal animal = new Dog(); // Possible
animal = new Animal(); // Possible too
Although in this case, Animal
probably deserves to be abstract
(so you wouldn't be able to create one in the first place - you'd have to create a concrete class).
Upvotes: 3
Reputation: 174
if you are new to coding I don't want to throw technical things at you. so i'll explain it this way.
you can always convert in 2 cases. 1. the object you are converting from, and to, have a predefined converter created and called 2. the object you are trying to convert from is made up of the smaller object you are trying to convert to.
such as
in life we can assume
Orange : Fruit
so we can say
eat((Fruit)orange)
because orange is made up of a lower class Fruit.
however to convert a Fruit to Orange you cannot do because Orange is more complex than just Fruit, and also who is to say this Fruit wasn't a Banana, 2 very different things, although still Fruit
As Commented "All oranges are fruit, but not all fruit are oranges"
Upvotes: 0
Reputation: 7824
The problem is that C is of type B, but B is not of type C.
It would work if you wrote it like this:
B b = new C();
b = new B();
Upvotes: 0