mani654
mani654

Reputation: 51

Preventing Inheritance?

How can i prevent a class from from being inherited without using Sealed Keyword?

Thanks in advance.

Upvotes: 1

Views: 2660

Answers (5)

manoranjan
manoranjan

Reputation: 11

You can achieve this by using private constructor, something along the lines:

public class NonInheritableClass
{
    static NonInheritableClass GetObject()
    {
        return new NonInheritableClass();
    }

    private NonInheritableClass()
    { 
    }
}

Upvotes: 1

payo
payo

Reputation: 4561

You can use private constructors

class Base
{
  private Base() {}
}

class Derived : Base
{
  // derp
}

Then provide a utility to creaet Base objects (like static methods on Base that have access to the private ctor

class Base
{
  private Base() {}

  public static Base CreateBase() { return new Base(); }
}

Also, if you want to be able to derive from this class, but you don't want other people doing that, you can make your class internal (or even the ctor internal)

class Base
{
  internal Base() { }
}

class Derived : Base
{
}

// in another assembly

class MyOwnDerived : Base
{
  // derp
}

Upvotes: 4

Alan Delimon
Alan Delimon

Reputation: 817

Throwing an exception in the constructor will work.

I agree though - why not use sealed? It's there for that reason.

Unless you' are trying to do something else, and if that's the case, there is probably a better solution too.

Upvotes: 0

Matthew Sanford
Matthew Sanford

Reputation: 1099

Another way is you can make a static method that returns an object of your type and then make the constructor private. This has the advantage that it will create a compile time error instead of a run time error.

Upvotes: 9

Steve Danner
Steve Danner

Reputation: 22158

In your class's constructor:

public MyUnsealedClass()
{
  if (this.GetType() != typeof(MyUnsealedClass))
      throw new Exception("Don't do that");
}

Why not use the sealed keyword though?

Upvotes: 11

Related Questions