base (C# Reference)
The base
keyword is used to access members of the base class from within a derived class. Use it if you want to:
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.
The base class access is permitted only in a constructor, in an instance method, and in an instance property accessor.
Using the base
keyword from within a static method will give an error.
The base class that is accessed is the base class specified in the class declaration. For example, if you specify class ClassB : ClassA
, the members of ClassA are accessed from ClassB, regardless of the base class of ClassA.
Example 1
In this example, both the base class Person
and the derived class Employee
have a method named GetInfo
. By using the base
keyword, it is possible to call the GetInfo
method of the base class from within the derived class.
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee : Person
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass
{
static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}
/*
Output
Name: John L. Malgraine
SSN: 444-55-6666
Employee ID: ABC567EFG
*/
For additional examples, see new, virtual, and override.
Example 2
This example shows how to specify the base-class constructor called when creating instances of a derived class.
public class BaseClass
{
int num;
public BaseClass()
{
Console.WriteLine("in BaseClass()");
}
public BaseClass(int i)
{
num = i;
Console.WriteLine("in BaseClass(int i)");
}
public int GetNum()
{
return num;
}
}
public class DerivedClass : BaseClass
{
// This constructor will call BaseClass.BaseClass()
public DerivedClass() : base()
{
}
// This constructor will call BaseClass.BaseClass(int i)
public DerivedClass(int i) : base(i)
{
}
static void Main()
{
DerivedClass md = new DerivedClass();
DerivedClass md1 = new DerivedClass(1);
}
}
/*
Output:
in BaseClass()
in BaseClass(int i)
*/
C# language specification
For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.
See also
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for