简体   繁体   中英

Can a sealed or static class be declared inside a sealed class in C#?

These are two separate questions:

  1. Can a class marked as sealed be present inside a sealed class?
  2. Can a class marked as static be present inside a sealed class?

These questions are just out to have better understanding of the core concepts. Can anyone highlight the practical usage of above concept?

C# supports the concept of a nested class. Using term "super class" is not appropriate, that implies that the nested class has an inheritance relationship. There is none whatsoever, the term "outer class" is appropriate.

It is useful only to control accessibility. A nested class has access to the private members of the outer class. And most useful, you can declare a nested class private so it is completely invisible to any code outside of the outer class. A much stronger guarantee than the default internal provides.

So what follows is that declaring the outer class sealed has no consequence to the nested class. Easy to see for yourself by just experimenting with it.

Yes. You can place a static class inside a sealed class .

The following is perfectly valid:

public sealed class SealedClass
{
    public static class StaticClass 
    { 

    }
}

The Vice-versa is also valid:

public static class SealedClass
{
    public sealed class StaticClass 
    { 

    }
}

What is sealed class?

They cannot be inherited. It improves the performance when compiling and runtime.

What is static class?

They cannot be instantiated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM