yanhua yanhua - 2 months ago 21
C# Question

Implicit Casting

I have a class

A
that inherits from
B
:

public class A : B { }
A a = new A();

List<B> list= new List<B> {
a
}


This gives me an error saying that
a
cannot be implicitly cast to
B
.

When I try to cast
a
to
B
:

(B) a


Visual Studio says the cast is
redundant
and tells me to remove it.

Can someone please explain this?

Image 1

Image 2

Answer Source

As the error shows, the MainMenu in your code is referring not to your MainMenu class, but to System.Windows.Forms.MainMenu, which does not inherit from UserControl.

To remedy this, use a qualified namespace:

controls["MainMenu"] = new Assignment3.Views.MainMenu();

Or alternatively, you could use a different class name that doesn't conflict with a built-in class name.