yanhua
yanhua

Reputation: 25

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

Upvotes: 0

Views: 57

Answers (3)

JLRishe
JLRishe

Reputation: 101652

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.

Upvotes: 2

jdweng
jdweng

Reputation: 34421

Try these changes

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

        List<B> b = null;

        public A()
        {
            b = new List<B>() { a };
        }
    }

Upvotes: 0

Geir Sagberg
Geir Sagberg

Reputation: 9821

From your screenshots, looks like you are mixing the System.Windows.Forms.MainMenu class with your own Assignment3.Views.MainMenu.

Try this:

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

Upvotes: 1

Related Questions