简体   繁体   中英

When inheriting from a framework control, should I call the base constructor?

I'm inheriting from a ListBox. Do I need to explicitly call the base constructor?

public class MyListBox : ListBox
{
   public MyListBox() : base()
   {
   }

   // or 

   public MyListBox()
   {
   }
}

The two options you listed will compile to identical code.

The only reason to include : base() is to explicitly denote that you are calling the base classes default constructor instead of some other constructor, by design. If left off, this happens automatically. As such, this is completely optional.

However, if you want to use a constructor other than the parameterless constructor of the base class, you would have to explicitly state this, ie:

public MyListBox() : base("Foo")
{ }

This would explicitly use a constructor which accepted a string as an argument.

A call of the default constructor is performed implicitly if you do not specify which constructor to call. When you omit a constructor call, C# will call the default one for you; if there is no default constructor, your code would not compile.

10.11.1 Constructor initializers

All instance constructors (except those for class object) implicitly include an invocation of another instance constructor immediately before the constructor-body.

[...]

If an instance constructor has no constructor initializer, a constructor initializer of the form base() is implicitly provided.

According to the C# spec, the two code snippets from your question are equivalent to each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM