开发者

Define private / public type of struct

I want to define a variable that will store two parameters — username and access level. In order to do this, I choose to use the struct, that I declare in App.cs file and variable from a type of this struct that I fill-in on success authorization.

Here is some code example:

struct AuthSession {
    string username;
    string accessLevel;
}

public AuthSession userSession;

Important! The variable userSession must be accessi开发者_开发问答ble from/to all classes in order to supply the ability to check user session each time and in each place I need.

My questions:

  1. Should I type private / public in the structure definition? E.g. public struct AuthSession vs. struct AuthSession.

  2. If I don't type private / public in the structure definition does it set some encapsulation level by default?


By default if you don't specify a visibility modifier on a top-level class/struct it is considered internal. Nested class/struct default to private.

  • struct AuthSession means internal i.e. visible only inside the assembly in which it is declared.
  • public struct AuthSession means public i.e. accessible from other assemblies as well.

Note that this is not the same with the struct fields (username and accessLevel). If you don't specify a visibility modifier for them they are private.


Are you sure you want a struct? If you want to store state in the struct and pass it around and populate it with values you might be surprised by the behaviour. I'd suggest using a class instead.

Consider the following example:

class Program
    {
        struct AuthSession
        {
            public string username;
            public string accessLevel;
        }

        class AuthSession2
        {
            public string Username { get; set; }
            public string AccessLevel { get; set; }
        }

        static void Main(string[] args)
        {
            AuthSession session = new AuthSession();
            AuthSession2 session2 = new AuthSession2();

            DoStuff(session);
            DoStuff(session2);

            Console.WriteLine(session.username + " " + session.accessLevel);
            Console.WriteLine(session2.Username + " " + session2.AccessLevel);
        }

        static void DoStuff(AuthSession session)
        {
            session.username = "a";
            session.accessLevel = "a";
        }

        static void DoStuff(AuthSession2 session)
        {
            session.Username = "a";
            session.AccessLevel = "a";
        }
    }

You'll note if you run this example the Main method will only have values for the class AuthSession2, not the struct.

Is that really want you want?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜