Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritable only inside assembly in C#

In C# Is there way to specify a class to be inherited only by a class present in the same assembly and for other assemblies should behave like a public sealed type.

like image 283
Ramesh Avatar asked Mar 10 '09 13:03

Ramesh


People also ask

Can you inherit private members of a class in C#?

Yes, The are inherited. But you cannot access them as they are private :).

What classes are not inheritable?

A Static class and a Sealed class cannot be inherited.

Are private class members inherited to the derived class?

The derived class doesn't "inherit" the private members of the base class in any way - it can't access them, so it doesn't "inherit" them.

How do you prevent a class from being inherited in C#?

In C# you use the sealed keyword in order to prevent a class from being inherited. In VB.NET you use the NotInheritable keyword. In Java you use the keyword final .


2 Answers

I think Eric Lippert gets the defining quotes here:

  • Preventing third-party derivation part one
  • Preventing third-party derivation part two
like image 111
Marc Gravell Avatar answered Oct 13 '22 03:10

Marc Gravell


The language itself doesn't have anything that makes this easy, but you should be able to do this by making your constructors internal. If you do this, however, you won't be able to new it up from external assemblies, so you'll have to add a factory method.

public class Foo
{
    internal Foo()
    {
    }

    public Foo Create()
    {
        return new Foo();
    }
}

Here's an alternative that lets you new up the class in external assemblies

public sealed class Foo : FooBase
{

}

public class FooBase
{
    internal FooBase() { }
}

One question you might ask yourself, however, is exactly why you want the class to be sealed. Sometimes it's inevitable, but I have seen the sealed keyword get abused so often that I thought I'd bring it up. Often, developers will seal classes because they are overprotective of their code. Most of the time, if a class is well designed, it doesn't need to be sealed.

like image 32
Michael Meadows Avatar answered Oct 13 '22 04:10

Michael Meadows