Reasons to use private class

13

When I started in the area, in an OOP course the teacher explained about access modifiers ...

I remember that the same day he said that it would be possible to create a private class, but he did not see a reason for doing so.

Why can you declare private classes? Can I use them in any way? If so, how?

Note: I ask for no amplitude intentions. If you consider too broad, please give me examples ...

    
asked by anonymous 11.04.2018 / 21:59

1 answer

17

Private class is very little useful because it is only available inside another class, that is, only the outer class can instantiate an object of the inner class that is private. Not even returning an object of this type out of the class is possible because the type does not exist outside of it.

When the type is really only useful internally you do not have to let the class be accessible from the outside. The less scoped the less errors you may have in your code, the less pollution the namespace will have, so it is easier to find what you want.

There is little reason, but there are cases for its use. This is done to hide implementation details . So one day you can change what you want without worrying. Everything that is exposed out of the class becomes a contract that you have to respect under penalty of breaking the existing codes.

A simplified and unnecessary example in this context, just to illustrate:

public class Classe {
    Temp temp = new Temp();
    public string Texto { get => temp.Str; set => temp.Str = value; }
    public int Valor { get => temp.I; set => temp.I = value; }

    private class Temp {
        public string Str { get; set; }
        public int I { get; set; }
    }
}

You can not create an object of type Temp outside this class.

One thing few people know is that the class default is internal , that is, it is only accessible within the code assembly itself. To make the class accessible for every application, you must use the public attribute on it.

In other languages an inner class may have other functions, and if you try to learn from them, you will not be learning how it works in C #, which is just that.

    
11.04.2018 / 22:37