Posts

Showing posts from May 16, 2025

Understanding the Base Keyword in C# with a Practical Example

  Understanding the Base Keyword in C# with a Practical Example When working with inheritance in C#, the  base  keyword is an essential tool that helps you reuse and extend functionality from a parent class. It allows a derived class to call constructors and methods defined in its base class, ensuring proper initialization and consistent behavior. In this blog, we will explore the  base  keyword through a simple but illustrative example involving employee management.   What is the Base Keyword? The  base  keyword refers to the immediate parent class of a derived class. It lets you: Call the base class constructor from the derived class. Access or invoke overridden methods from the base class inside the derived class. This helps avoid duplication and ensures that the base class is properly initialized and its logic is preserved.   Real-World Scenario: Employees and Managers Let’s consider a company where we h...

Extension Methods in C#

Extension Methods in C# Extension methods in C# provide a way to add new functionality to existing types without altering their source code or creating a new derived type. This feature is particularly useful when you want to extend the capabilities of a class you do not own, such as system-defined types like string, int, or custom types from libraries. An extension method is defined as a static method in a static class, but it behaves as if it were an instance method on the type being extended. This allows for cleaner syntax and more intuitive method chaining. How Extension Methods Work To define an extension method, you create a static method inside a static class. The first parameter of the method specifies the type it extends and is preceded by the this keyword. Here’s a simple example: public static class StringExtensions {     public static bool IsNullOrEmpty(this string value)     {       ...

Static Classes in C#

Static Classes in C# In C#, a  static class  is a special kind of class that cannot be instantiated and can only contain static members. It is typically used for utility methods, helper functions, configuration constants, or extension methods. What is a Static Class? A static class is declared using the static keyword. Once defined, you  cannot create an object  from a static class using the new keyword. All members of a static class must also be marked as static. Example: public static class MathHelper {     public static int Square(int number)     {         return number * number;     } } Explanation: In this example, the MathHelper class contains a static method called Square that takes an integer and returns its square. Since the class is static, you don’t need to create an object to use it. You can simply call: int result = MathHelper.S...