
Show difference between base and this. C# program that uses base and this keywords And then it gets the this _value, which is 7.ĭisambiguate: This is a fancy word that means "to make clear" which entity you are referring to. Output: The program accesses first the base _value, which equals 6. They eliminate confusion as to which member we want.ĭerived: When we have a derived class, we can use a "base" expression to directly access the base class. In a derived class, the base and this keywords can be used to reference members. Tip: This does the same thing conceptually as base but for the same class, not the parent class.īase vs. You can use this() with the argument list of another constructor declaration in the same exact type. There is another keyword that can be used in a constructor initializer in the same way as base(). Note: For non-default constructors, you must specify the base constructor initializer with valid arguments. The compiler inserts the constructor call at the start of the method body. In the B constructor, we use base initializer syntax. We specify that the base class constructor is called upon entry to the derived constructor. The "B: A" syntax indicates that class B derives from class A.Įxplanation: In the example, the constructor in class B calls into the constructor of class A using base initializer syntax. Class A is the parent or base class for class B, which is referred to as the derived class.

In this program, class A and class B both introduce constructors. Create a new instance of class A, which is the base class. Public class B : A // This class derives from the previous class.Ĭonsole.WriteLine("Derived constructor B()")
#Swift constructor code
Executes some code in the constructor.Ĭonsole.WriteLine("Base constructor A()") Public class A // This is the base class. Based on:Ĭ# program that uses base constructor initializer Tip: This initializer is specified by adding a colon and the base keyword after the derived constructor parameter list.

The derived class must use a base constructor initializer, with the base keyword, in its constructor declaration. Both of the classes use a non-default, parameterful constructor. The program uses a base class and a derived class. Note: In a class, we can also access fields and other members (like methods) with the "base" and "this" keywords.Įxample. When the default constructor isn't present, the custom base constructor can, with base, be referenced. Base refers to base class.Ī derived class constructor is required to call the constructor from its base class. This C# program introduces the base-keyword and compares it to the this-keyword.
