简体   繁体   中英

What is the benefit of nesting static classes without methods?

I came across a code example like this:

It's a nested static class without any methods, just variables.

public static class StaticConstants
{
    public static class File
    {
        public static string UserFile = "userdata.txt";
        public static string UserSettings = "usersettings.txt";
    }
    public static class API
    {
        public static string ApiUrl = "dummysite.com";
        public static string ApiEndPoint = "api/anEndpoint";
    }
}

I know you access your static variables now via StaticConstants.Api.ApiUrl

Is there any point in doing this (performance wise)? Or is it 100% personal preference? Is it a good coding habit to do this or is better to create 2 static files with static variables?

It allows you to access static data in hierarchical way with the dot notation:

var x = StaticConstants.File.UserFile;

If this data is really meant to be constant, they should have used C# constants. Those are static as well.

public const string UserFile = "userdata.txt";

If const cannot be used because the initialization needs to run some code, like creating objects, then the readonly keyword should be used.

public static readonly Font DefaultFont = new Font("Arial", 12f);

It makes no difference for the compiled code whether the source code was in one or several files. It is just a matter of organizing the source code. It also makes no difference performance wise.

Nesting classes and types in general (whether static or not) has an influence on the visibility scope and accessibility but does not influence the semantics (ie the meaning, what it does).

Ie, a non-static nested class does not automatically result in a nested object and it cannot access non-static (instance) members of the surrounding class directly. It must do so through a reference to the surrounding object (as for any other object). If an object is assigned to a field or property of the surrounding class, then it will be nested whether the type is nested or not.

Nesting types and nesting instances is not related.

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