I've recently started learning C# and I'm confused about something. The documentation for static classes tells me that they can only contain static members. Yet I can define non-static nested classes and structs within my static class.
I'm guessing that class/struct definitions don't count as members, but why is this allowed? If a nested class of a static class can be instantiated, doesn't that contradict the point of a static class? Am I misunderstanding something obvious here?
In C# nested classes are not subclasses, the surrounding class is more like another namespace. You dont have access to an instance of the outer class from within the inner class(as opposed to f.e. Java). That's why static classes can contain nested types.
A famous example, the LINQ class Enumerable which is static. It contains many helper classes:
public static class Enumerable
{
// many static LINQ extension methods...
class WhereEnumerableIterator<TSource> : Iterator<TSource>
{
// ...
}
internal class EmptyEnumerable<TElement>
{
public static readonly TElement[] Instance = new TElement[0];
}
public class Lookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>, ILookup<TKey, TElement>
{
// ...
}
// many others
}
So the surrounding static class is a logical container for the inner class. It belongs there because it is used from the static class and often not accessible from somewhere else(if not public).
But you're right, it's a lack of documentation. They should have said:
Contains only static members or nested types
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With