0

I am curious to know if there are any samples in c#. I can't think of a single sample forbidding inheritance rather than some commercial intentions, so I would like to know some real world examples in c# itself.

I know about sealed classes, I'm just looking for some examples in c# itself, something rather than value types and structs which are implicitly sealed.

Hossein
  • 24,202
  • 35
  • 119
  • 224
  • 2
    I'm not sure about "commercial intentions", but `sealed` classes prevent [Fragile Base Class](http://en.wikipedia.org/wiki/Fragile_base_class) issues. One day to day example is the [`Thread`](http://msdn.microsoft.com/en-us/library/system.threading.thread(v=vs.110).aspx) class - you really don't want to inherit it and change its behaviour. – Honza Brestan Jul 08 '14 at 15:39
  • Aha, :) that makes sense now, your thread example really makes sense. And thanks for the link:) – Hossein Jul 08 '14 at 15:45
  • 1
    No problem :) If you want a complete list, you can browse or download .NET reference sources and search for all other cases http://referencesource.microsoft.com/ – Honza Brestan Jul 08 '14 at 15:46

3 Answers3

4

Yes it has. All the classes that are sealed, they cannot be used as base classes.

For more information about sealed classes, please have a look here.

Some examples of sealed classes in .NET are the following:

Christos
  • 53,228
  • 8
  • 76
  • 108
  • !i know about sealed classes, im just loking for some examples in c# itself, something rather than value types and strucs wich are implicitly sealedCan you name some? – Hossein Jul 08 '14 at 15:38
  • Sure thing, `System.String`, as already p.s.w.g has already pointed out is one of them. – Christos Jul 08 '14 at 15:40
3

You cannot inherit from any struct, sealed class, or static class. C# also prohibits using a number of 'special' types including Delegate and Enum, as it provides other constructs for using these.

The most obvious example that comes to my mind is System.String.

If you were to try to inherit from it like this:

public class CustomString : String { }

You'll see this error:

'CustomString': cannot derive from sealed type 'string'

And there are many other examples in the .Net framework. I did a quick comparison using reflection and in mscorlib (v4.0) alone there are 856 sealed public types, compared to 619 non-sealed public types (which includes interfaces).

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
1

Besides sealed class, static class cannot also be inherited, see about. E.g : System.Linq.Enumerable.

public static class Inherited : System.Linq.Enumerable
{
}

This is not working too.

Community
  • 1
  • 1
Perfect28
  • 11,089
  • 3
  • 25
  • 45