简体   繁体   中英

Issues accessing C# class from another .cs file

I'm creating a login form that, when the authentication is completed successfully, inserts 3 parameters (userID, user and displayName) on the following class:

userSession.cs

namespace Summaries
{
    /// <summary>
    /// Stores the user information sent by the server
    /// </summary>
    class UserSession
    {
        public int userID { get; set; }
        public string user { get; set; }
        public string displayName { get; set; }
    }
}

When I'm on the login form, I can write/read from the class, but when I try to read on my main.cs file it returns null.

main.cs

private void main_Shown(object sender, EventArgs e)
{
    UserSession session = new UserSession();
    sessionLabel.Text += session.displayName;
}

It is probably just a newbie mistake, but can you show me how to access the values or, if this approach is not ideal/possible, a way to store and access the values between forms?

EDIT : I've already tried different approaches to "initialize" it. I also tried UserSession session; but got a "Use of unassigned local variable 'session'"

My workaround : Instead of using a class from another file to try and store the user information, I decided to pass the information to the other form at the moment of the call:

login.cs

private void loginBTN_Click(object sender, EventArgs e)
{
        serverResponse response;
        userSession session;

        string username = usernameBox.Text;
        string password = passwordBox.Text;
        string jsonResponse = LoginValidation(username, password);
        response = JsonConvert.DeserializeObject<serverResponse>(jsonResponse);

        if (response.status)
        {
            session = JsonConvert.DeserializeObject<userSession>(jsonResponse);
            main mainForm = new main(session.userID, session.user, session.displayName);
            this.Hide();
            mainForm.Show();
        }
        else
        {
            ...
        }
}

    private class userSession
    {
          public int userID { get; set; }
          public string user { get; set; }
          public string displayName { get; set; }
    }

    private class serverResponse
    {
           public bool status { get; set; }
           public string errors { get; set; }
    }

main.cs

private int userID;
private string user;
private string displayName;

/// <summary>
/// Main function from  the dashboard form.
/// </summary>
/// <param name="id">The user id retrived from the database</param>
/// <param name="username">The username retrived from the database (login name)</param>
/// <param name="display">The name to be displayed that was retrived from the database</param>
public main(int id, string username, string display)
{
    InitializeComponent();
    userID = id;
    user = username;
    displayName = display;
}

Using this approach, I can get the values to my main.cs file but with the downside that I have to pass them whenever I want to open/show a different form.

There are two things to look for in your question:

In UserSession you could add explicit public or private and a constructor - a special method used to "construct" instances of a class.

public class UserSession
{
    public int UserID { get; set; }
    public string User { get; set; }
    public string DisplayName { get; set; }

    public UserSession(int id, string user, string displayName) 
    {
         UserID = id;
         User = user;
         DisplayName = displayName;
    }
}

Explicitly specifing private (default) or public is good for maintainability and is kind of a standard in C#.

And when you want UserSession object call it like this:

var user = new UserSession(id, user, displayName);

where id , user and displayName are other variables or constants.

Effect is the same as with assigning properties by hand after calling new UserSession() (without any parameters), but in most cases using constructor is considered better practice.

In your case however

private void main_Shown(object sender, EventArgs e)
{
    UserSession session = new UserSession(**id**, **name**, **displayName**);
    sessionLabel.Text += session.displayName;
}

You need to provide those variables or constants that are added to constructor to that method. If your application is a WebForms, then you should have it somewhere and you need to provide it eg in EventArgs . You can do the same if you are in desktop environment.

However, in desktop environment you have another viable option that will work fine provided that you have only one user . You can create field in a class that owns the method from above. And assign fields of UserSession objects as you go.

You could also (in one user scenario) make UserSession a static class with public properties and no constructor and then you would again assign to properties of the class as soon as you have the data about the user. You wouldn't have to create any instance nor filed then, because static fields are accessible by their class name (and there is only one instance of this class program-wide, hence only one user).

.... before ....
UserSession.DisplayName = "user";
... then ...
private void main_Shown(object sender, EventArgs e)
{
    sessionLabel.Text += UserSession.DisplayName;    
}

This is not a recommended option, but I include it for completeness.

new UserSession(); 

Creates a new instance and for all the properties in the class have the default values of each. Therefore, you should assign values for each property after instantiation.

private void main_Shown(object sender, EventArgs e)
{
    UserSession session = new UserSession();
    session.userID = "<user id>";
    session.user = "<user>";
    session.displayName = "<displayName>";
    sessionLabel.Text += session.displayName;
}

In c#, you can define any class as static class, so it's public properties could be accessed by another class directly.

Cheers...

Static classes and static class members

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