Making a class not inherited

12,339

Solution 1

sealed is the word you're looking for, and a link for reference

public sealed class MyClass
{

}

And then just create your class as normal, however you won't be able to inherit from it.

You can however still inherit from a different class like so

public sealed class MyClass : MyBaseClass
{

}

Solution 2

Adding to the PostMan's answer, we can achieve the same by making the Class Constructor Private.

class NotInheritable
    {

        private NotInheritable()
        {
            //making the constructor private
        }
    }

 class Derived : NotInheritable { }

Now the class NotInheritable will not be inheritable, as the compiler will prompt the error:

NotInheritable.NotInheritable() is inaccessible due to its protection level.

Share:
12,339
Troy
Author by

Troy

.Net 4 rookie

Updated on June 15, 2022

Comments

  • Troy
    Troy about 2 years

    I am trying to create a c# class, but I dont want it to be inherited. How can I accomplish that?