Method Hiding is a process in which we hide base Class Members and presents the derived class members.
Use the new keyword to hide a Base Class member, you will get a compiler warning if you
miss the new keyword.
Code Example without Hiding of method :-
In the below example we use a Student Base Class and two child classes RegularStudent and DistanceStudent which are inherits from
Student base class.We want to print full name of the students so here we use a Method PrintDetails() used for printing the full name of students.
public class Stdent
{
public string _firstname;
public string _lastname;
public void PrintDetails()
{
Console.WriteLine(_firstname + " " + _lastname);
}
}
public class RegularStudent : Student
{
}
public class DistanceStudent : Student
{
}
class Program
{
static void Main(string[] args)
{
RegularStudent objRegularStudent = new RegularStudent();
objRegularStudent._firstname = "John";
objRegularStudent._lastname = "Karter";
objRegularStudent.PrintDetails();
DistanceStudent objDistanceStudent = new DistanceStudent();
objDistanceStudent._firstname = "Marry";
objDistanceStudent._lastname = "Martin";
objDistanceStudent.PrintDetails();
Console.ReadKey();
}
}
Output of the Program
John Karter
Marry Martin
Code Example with method Hidding
public class Student
{
public string _firstname;
public string _lastname;
public void PrintDetails()
{
Console.WriteLine(_firstname + " " + _lastname);
}
}
public class RegularStudent : Student
{
public new void PrintDetails()
{
Console.WriteLine(_firstname + " " + _lastname + "-Regular Student");
}
}
public class DistanceStudent : Student
{
}
class Program
{
static void Main(string[] args)
{
RegularStudent objRegularStudent = new RegularStudent();
objRegularStudent._firstname = "John";
objRegularStudent._lastname = "Karter";
objRegularStudent.PrintDetails();
Student objStudent = new DistanceStudent();
objStudent._firstname = "Marry";
objStudent._lastname = "Martin";
objStudent.PrintDetails();
Console.ReadKey();
}
}
In the above code we hide the Base class method with new keyword used in derived class method.
Different ways to invoke a hidden base class member from derived class.
About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the
applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server,
EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.