1. new Keyword
The new keyword is used for creating instances of a class or invoking constructors. It can also be used to hide a member inherited from a base class.
Example 1: Creating an Object
class Person
{
public string Name;
public Person(string name)
{
Name = name;
}
}
Person person = new Person("John Doe");
Console.WriteLine(person.Name); // Output: John Doe
Example 2: Hiding a Member
When using inheritance, you can use the new keyword to hide a member of the base class with a new member of the derived class.
class BaseClass
{
public void Display()
{
Console.WriteLine("Base class Display");
}
}
class DerivedClass : BaseClass
{
public new void Display()
{
Console.WriteLine("Derived class Display");
}
}
DerivedClass obj = new DerivedClass();
obj.Display(); // Output: Derived class Display
2. this Keyword
The this keyword refers to the current instance of the class. It is commonly used to distinguish between class members and parameters with the same name.
Example: Using this to Differentiate Between Members and Parameters
class Person
{
private string name;
public Person(string name)
{
this.name = name; // 'this' refers to the instance variable, 'name' refers to the parameter
}
public void PrintName()
{
Console.WriteLine(this.name);
}
}
Person person = new Person("Alice");
person.PrintName(); // Output: Alice
3. base Keyword
The base keyword is used to refer to the members (methods, properties, etc.) of the base class from within a derived class. It is commonly used to call base class constructors or override methods.
Example: Using base to Call the Base Class Constructor
class Animal
{
public string Name;
public Animal(string name)
{
Name = name;
}
}
class Dog : Animal
{
public Dog(string name) : base(name) // Calls the base class constructor
{
}
public void Bark()
{
Console.WriteLine(Name + " says Woof!");
}
}
Dog dog = new Dog("Rex");
dog.Bark(); // Output: Rex says Woof!
Example: Using base to Call a Base Class Method
class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal sound");
}
}
class Dog : Animal
{
public override void Speak()
{
base.Speak(); // Calls the base class Speak method
Console.WriteLine("Dog barks");
}
}
Dog dog = new Dog();
dog.Speak();
// Output:
// Animal sound
// Dog barks
4. namespace Keyword
A namespace is used to organize code into logical groups. This helps avoid name conflicts, especially when your code base grows or integrates with libraries.
Example: Declaring a Namespace
namespace MyApplication
{
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!");
}
}
}
Namespaces can also be nested, and their usage can help prevent class name conflicts when multiple libraries or parts of a project contain classes with the same name.
5. abstract Keyword
The abstract keyword is used to declare abstract classes and methods. An abstract class cannot be instantiated directly, and any class that inherits it must implement its abstract methods.
Example: Abstract Class and Method
abstract class Animal
{
public abstract void MakeSound(); // Abstract method with no implementation
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Woof!");
}
}
Dog dog = new Dog();
dog.MakeSound(); // Output: Woof!
An abstract class can have regular (non-abstract) methods as well, but any abstract methods must be implemented by the derived class.
6. virtual Keyword
The virtual keyword is used to allow a method or property to be overridden in a derived class. By default, methods in C# are not virtual, so to enable method overriding, you need to mark the method as virtual.
Example: Virtual Method
class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal sound");
}
}
class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Dog barks");
}
}
Dog dog = new Dog();
dog.Speak(); // Output: Dog barks
7. sealed Keyword
The sealed keyword is used to prevent further inheritance of a class or overriding of a method. Once a class or method is marked as sealed, no other class can inherit from it, and no derived class can override a sealed method.
Example: Sealed Class
sealed class Animal
{
public void Speak()
{
Console.WriteLine("Animal sound");
}
}
// Error: Cannot inherit from sealed class 'Animal'
// class Dog : Animal { }
Example: Sealed Method
class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal sound");
}
}
class Dog : Animal
{
public sealed override void Speak() // Sealed method
{
Console.WriteLine("Dog barks");
}
}
// Error: Cannot override sealed member 'Dog.Speak'
// class Bulldog : Dog { public override void Speak() { } }
8. static Keyword
The static keyword denotes that a member belongs to the type itself, rather than to instances of the type. static members can be methods, properties, fields, or even entire classes.
Example: Static Members
class MathUtility
{
public static double Pi = 3.14159;
public static double Square(double number)
{
return number * number;
}
}
Console.WriteLine(MathUtility.Pi); // Output: 3.14159
Console.WriteLine(MathUtility.Square(5)); // Output: 25
A static class cannot be instantiated, and all members of a static class must also be static.
Example: Static Class
static class Helper
{
public static void PrintMessage(string message)
{
Console.WriteLine(message);
}
}
// Cannot instantiate static class
// Helper helper = new Helper(); // Error
Helper.PrintMessage("Hello from static class!"); // Output: Hello from static class!
Conclusion
These keywords (new, this, base, namespace, abstract, virtual, sealed, static) are essential tools in object-oriented programming in C#. Understanding when and how to use these keywords correctly helps in writing better-structured, more efficient, and maintainable code.
newcreates objects and hides base class members.thisrefers to the current instance.baseaccesses base class members.namespaceorganizes code.abstractdefines abstract classes and methods.virtualallows method overriding.sealedprevents further inheritance or overriding.staticdefines members that belong to the type rather than an instance.
In C#, many object-oriented keywords can be combined to leverage the full power of inheritance, polymorphism, and code organization. Below are explanations and examples of how combinations of new, this, base, namespace, abstract, virtual, sealed, and static can be used together effectively.
1. Combination of this and new
Using this in combination with new helps distinguish between instance members and constructor parameters or other local variables when creating objects.
Example: Constructor and Instance Member Initialization
class Person
{
private string name;
public Person(string name) // Constructor parameter
{
this.name = name; // 'this' is used to refer to the instance member
}
public void PrintName()
{
Console.WriteLine(this.name);
}
}
Person person = new Person("Alice"); // 'new' creates the object
person.PrintName(); // Output: Alice
newis used to create thePersonobject.thisis used to disambiguate between the class membernameand the constructor parametername.
2. Combination of base, virtual, and override
A common combination is using base to call the base class implementation of a virtual method in an overridden method within a derived class.
Example: Base Method Call with virtual and override
class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal sound");
}
}
class Dog : Animal
{
public override void Speak()
{
base.Speak(); // Calls the base class method
Console.WriteLine("Dog barks");
}
}
Dog dog = new Dog();
dog.Speak();
// Output:
// Animal sound
// Dog barks
virtualallows the base class methodSpeakto be overridden.overrideallows the derived class to provide its specific implementation.basecalls the base class implementation ofSpeakbefore adding the derived class behavior.
3. Combination of abstract, override, and sealed
In C#, you can combine abstract methods in a base class with override in derived classes, and then use sealed to prevent further overriding.
Example: Abstract Method, Overriding, and Sealing
abstract class Animal
{
public abstract void MakeSound();
}
class Dog : Animal
{
public sealed override void MakeSound() // Seals the method to prevent further overrides
{
Console.WriteLine("Dog barks");
}
}
// Error: Cannot override sealed member 'Dog.MakeSound'
// class Bulldog : Dog { public override void MakeSound() { } }
abstractforces derived classes to implementMakeSound.overridein the derivedDogclass provides the implementation.sealedprevents further derived classes from overridingMakeSound.
4. Combination of static and namespace
static and namespace are commonly used together for utility classes that provide globally accessible methods and constants without needing to instantiate an object.
Example: Static Utility Class Inside a Namespace
namespace Utilities
{
static class MathHelper
{
public static double Pi = 3.14159;
public static double Square(double number)
{
return number * number;
}
}
}
using Utilities; // Using the namespace to access the static class
class Program
{
static void Main()
{
Console.WriteLine(MathHelper.Pi); // Access static field
Console.WriteLine(MathHelper.Square(5)); // Access static method
}
}
staticdefines a class (MathHelper) with static members that are accessed globally.namespacelogically organizes the static utility class.
5. Combination of abstract, virtual, and override
When designing a class hierarchy, you might use abstract to define methods that must be implemented, virtual to define methods with default behavior that can be optionally overridden, and override to provide specific implementations.
Example: Abstract and Virtual Method Combination
abstract class Shape
{
public abstract double Area(); // Must be implemented by derived classes
public virtual void DisplayShapeType()
{
Console.WriteLine("This is a shape");
}
}
class Circle : Shape
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
public override double Area() // Abstract method implemented
{
return Math.PI * radius * radius;
}
public override void DisplayShapeType() // Optional override of the virtual method
{
Console.WriteLine("This is a circle");
}
}
Circle circle = new Circle(5);
Console.WriteLine(circle.Area()); // Output: 78.5398 (Area of the circle)
circle.DisplayShapeType(); // Output: This is a circle
abstractforces derived classes to implementArea().virtualprovides a default implementation forDisplayShapeType().overrideallows derived classes likeCircleto customizeDisplayShapeType().
6. Combination of new, virtual, and override
In some cases, you might use new to hide a base class method while also overriding a virtual method from the base class.
Example: Hiding and Overriding Methods
class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal sound");
}
public void Eat()
{
Console.WriteLine("Animal eats");
}
}
class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Dog barks");
}
public new void Eat() // Hides the base class method
{
Console.WriteLine("Dog eats");
}
}
Dog dog = new Dog();
dog.Speak(); // Output: Dog barks
dog.Eat(); // Output: Dog eats
Animal animal = new Dog();
animal.Speak(); // Output: Dog barks (overridden method)
animal.Eat(); // Output: Animal eats (base class method)
newhides theEatmethod in the base class, but it does not override it.virtualallowsSpeakto be overridden.overrideprovides a specific implementation ofSpeakin theDogclass.
7. Combination of static, sealed, and base
static and sealed can be combined when defining utility classes that should not be inherited or instantiated. While base is generally not used with static classes, a sealed class with instance methods can still use base if it inherits from a non-static, non-sealed base class.
Example: Sealed Class with Base Class and Static Method
class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal sound");
}
}
sealed class Dog : Animal // Sealed class
{
public override void Speak()
{
base.Speak(); // Calls the base class Speak method
Console.WriteLine("Dog barks");
}
public static void DisplayInfo()
{
Console.WriteLine("This is a static method in a sealed class");
}
}
Dog dog = new Dog();
dog.Speak();
// Output:
// Animal sound
// Dog barks
Dog.DisplayInfo(); // Output: This is a static method in a sealed class
sealedprevents further inheritance of theDogclass.baseis used to call the base class implementation ofSpeak.staticdefines a method that belongs to theDogclass itself rather than an instance.