Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "base" syntax mean?

Tags:

syntax

c#

Can somone please tell me what does the syntax below means?

public ScopeCanvas(Context context, IAttributeSet attrs) : base(context, attrs)
{
}

I mean what is method(argument) : base(argument) {} ??

P.S This is a constructor of a class.

like image 681
Saeid Yazdani Avatar asked May 08 '12 17:05

Saeid Yazdani


People also ask

What does base () mean in C#?

base (C# Reference) The base keyword is used to access members of the base class from within a derived class: Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be called when creating instances of the derived class.

What is the difference between this and base in C#?

Calling a method on this will call the method in the same way as it would if you called it on a variable containing the same instance. base is a keyword that allows inherited method call, i.e. it calls the specified method from the base type. It too can only be used in a non-static method.

What is base constructor in C#?

In C#, both the base class and the derived class can have their own constructor. The constructor of a base class used to instantiate the objects of the base class and the constructor of the derived class used to instantiate the object of the derived class.

How would you call the base class constructor from the derived class in C #?

We have to call constructor from another constructor. It is also known as constructor chaining. When we have to call same class constructor from another constructor then we use this keyword. In addition, when we have to call base class constructor from derived class then we use base keyword.


2 Answers

The :base syntax is a way for a derived type to chain to a constructor on the base class which accepts the specified argument. If omitted the compiler will silently attempt to bind to a base class constructor which accepts 0 arguments.

class Parent {
  protected Parent(int id) { } 
}

class Child1 : Parent {
  internal Child1() { 
    // Doesn't compile.  Parent doesn't have a parameterless constructor and 
    // hence the implicit :base() won't work
  }
}

class Child2 : Parent {
  internal Child2() : base(42) { 
    // Works great
  }
}

There is also the :this syntax which allows chaining to constructors in the same type with a specified argument list

like image 186
JaredPar Avatar answered Sep 18 '22 13:09

JaredPar


Your class is likely defined like this:

MyClass : BaseClass

It derives from some other class. : base(...) on your constructor calls the appropriate constructor in the base class before running the code in your derived class's constructor.

Here's a related question.

EDIT

As noted by Tilak, the MSDN documentation on the base keyword provides a good explanation.

like image 28
zimdanen Avatar answered Sep 21 '22 13:09

zimdanen