C# Base

C# provides a base keyword to access base class properties in the chilled class. C# Base is almost similar to the super in java. It can only be used inside instance methods and constructors. It can't be used inside any static method like main.


C# Base class example: accessing parent's class fields
using System;
public class Animal 
{
            public string color="White";
}
public class Dog : Animal
{
            string color="Black";
            public void showColor()
            {
                        Console.WriteLine("parent class color :"+base.color);
                        Console.WriteLine("child class color :"+color);
            }
}
public class BaseClassExample
{
            public static void Main(string[] args)
            {
                        Dog d=new Dog();
                        d.showColor();
            }
}
Output
parent class color :White
child class color :Black      
C# Base Example: calling Parent class methods
using System;
public class Animal 
{
            public void eat()
            {
                        Console.WriteLine("eating normal food...");
            }
}
public class Dog: Animal
{
            public void eat()
            {
                        Console.WriteLine("eating Bread");
                        base.eat();
            }
}
public class BaseClassExample
{
            public static void Main(string[] args)
            {
                        Dog d=new Dog();
                        d.eat();
            }
}
Output
eating Bread
eating normal food...



ADVERTISEMENT
ADVERTISEMENT