0

Is something like this possible in C#? What about CLR in general?

public sealed-outside class MySample
{
}
Den
  • 1,827
  • 3
  • 25
  • 46
  • Simple answer: no. What are you trying to achieve that would lead you to want to do that? I suspect a public interface and internal classes would fit your needs, – David Arno May 23 '15 at 21:09
  • @DavidArno This is a general question. My specific situation is a base non-abstract custom attribute that I would like to protect from being extended outside of the framework. It's not critical, I just wanted to know if there is a reason not to have this possibility in the language. – Den May 23 '15 at 21:23
  • You are probably looking for [AttributeUsage] with *Inherited* set to false. – Hans Passant May 23 '15 at 22:24
  • Add an abstract internal method. – CodesInChaos May 23 '15 at 23:00
  • @HansPassant Attribute *application* being inheritable has nothing to do with attribute *definition* being inheritable. – Den May 24 '15 at 13:02
  • Thanks for down-voting without explanation. – Den May 24 '15 at 13:05

1 Answers1

2

Only if you declare all constructors internal. Then only classes within the same assembly will be able to call a base class constructor which is required for inheritance. You may need some public static factory methods if others need to be able to create an instance.

If you want to be pedantic, this only prevents inheritance at the language level, not the CLR level. You could still technically create an inheriting class by declaring some mutually recursive constructors. Jon Skeet demonstrated this in an example.

Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
  • Thanks for suggestion. Unfortunately it's just a workaround. E.g. you cannot use a factory to instantiate custom attributes. – Den May 24 '15 at 13:04