Why do C # static classes contain non-static classes / structures?

I recently started to learn C #, and I'm somewhat confused. The documentation for static classes tells me that they can only contain static members. However, I can define non-static nested classes and structures in my static class.

I assume that class / structure definitions are not considered members, but why is this allowed? If a nested class of a static class can be created, does it contradict the point of the static class? I don’t understand something here?

+4
source share
2 answers

# , . ( f.e. Java). .

: LINQ class Enumerable, . :

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
}

, . , ( ).

, . :

+7

, / , . :

namespace StaticClasses
{
    class Program
    {
        static void Main(string[] args)
        {
            new Foo(); // Cannot create an instance of the static class 'Foo'
            new Foo.Bar(); // Cannot create an instance of the static class 'Foo.Bar'
            new Foo.Baz();
        }
    }

    static class Foo
    {
        public static class Bar
        {

        }

        public class Baz
        {

        }
    }
}

, () , .

+4

Source: https://habr.com/ru/post/1686950/


All Articles