DEV Community

Vivek Nariya
Vivek Nariya

Posted on

Classes - C# (Static, Abstract, Sealed)

Static Class

  • Constructor : can not have

  • Constructor Invocation : can not have

  • Purpose : Static classes are containers for utility methods and cannot be instantiated.

  • Common Features : Static members, static properties, static methods.

  • Note : No, in C#, a static class cannot contain non-static members, properties, or methods. Static classes are designed to provide a container for utility methods and constants and are typically used when you want to group methods and data that do not depend on instance data.

public static class MathUtils
{
    public static int Add(int a, int b)
    {
        return a + b;
    }
}
Enter fullscreen mode Exit fullscreen mode

Abstract Class

  • Constructor : can have

  • Constructor Invocation : Can be called through derived classes using base keyword

  • Purpose : Abstract classes provide blueprints for other classes and cannot be instantiated on their own.

  • Common Features : Abstract methods, virtual methods, protected members.

  • Note : Yes, an abstract class in C# can indeed have non-abstract methods, non-virtual methods, and non-protected members.

public abstract class Shape
{
    public abstract double CalculateArea();
    public abstract double CalculatePerimeter();
}
Enter fullscreen mode Exit fullscreen mode

Sealed Class

  • Constructor : can have

  • Constructor Invocation : Can be called normally

  • Purpose : Sealed classes prevent inheritance and provide complete implementations.

  • Note : When a class is declared as sealed using the sealed keyword, it means that the class cannot be inherited. In other words, it prevents other classes from deriving from it. Sealed classes are typically used when you want to prevent further specialization or modification of a class.

sealed class MyClass
{
    // Class members
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
karenpayneoregon profile image
Karen Payne

Would be nice to see more example and perhaps a GitHub repository for beginners to learn from.

Collapse
 
viveknariya profile image
Vivek Nariya

first