Checking for Sealed Classes in C# using Reflection

Learn how to use C# reflection to determine if a class is declared as `sealed` at runtime. This tutorial demonstrates a practical approach to inspecting type metadata, explaining how to check for the `sealed` modifier and its implications for inheritance and class design.



Checking if a C# Class is Sealed Using Reflection

This article demonstrates a C# program that uses reflection to determine whether a given class is declared as `sealed`. A `sealed` class in C# cannot be inherited from, preventing other classes from extending its functionality.

Understanding Sealed Classes

The `sealed` keyword in C# prevents inheritance. When a class is declared as `sealed`, no other class can inherit from it. This is useful for ensuring that a class's behavior remains consistent and cannot be unexpectedly modified by subclasses. It is commonly used to prevent unintended changes to specific functionalities. It is typically used for classes that are not intended to be extended.

Checking if a Class is Sealed

The provided C# program uses reflection to check if a class is sealed at runtime. Reflection is a powerful feature of C# allowing inspection and manipulation of type metadata during execution.


using System;

public class SealedClassChecker {
    public static bool IsClassSealed(Type type) {
        return type.IsSealed;
    }
    public static void Main(string[] args) {
        // ... (code to get the type using reflection and check if it's sealed) ...
    }
}

Explanation

  1. The program defines a method `IsClassSealed` that takes a `Type` object and returns a boolean indicating whether the type is sealed using the `IsSealed` property.
  2. The `Main` method takes the name of the class as a string input.
  3. It uses `Type.GetType()` (a reflection method) to obtain the `Type` object representing that class.
  4. It calls `IsClassSealed` to check whether the class is sealed.
  5. The result is then printed to the console.