Using strings from other C # classes

I have a class that asks what when called, the string is sent when requested / initialized.

class Checks
{
    public Checks(string hostname2)
    {
        // logic here when class loads

    }

    public void Testing()
    {
        MessageBox.Show(hostname2);
    }
}

How can I take the string "hostname2") in the constructor of the class and allow this string to be called anywhere in the "Checks" class?

eg. I call Checks (hostname2) from the Form1 class, now that the Checks class is initialized, I can use the hostname2 line in my Checks class as well

+5
source share
3 answers

Declare a member inside the class and assign the value that you passed to the member inside the constructor:

class Checks
{
    private string hostname2;

    public Checks(string hostname2)
    {
       this.hostname2 = hostname2; // assign to member
    }

    public void Testing()
    {
        MessageBox.Show(hostname2);
    }
}

If you also need external access, do this property:

class Checks
{
    public string Hostname2 { get; set; }

    public Checks(string hostname2)
    {
       this.Hostname2 = hostname2; // assign to property
    }

    public void Testing()
    {
        MessageBox.Show(Hostname2);
    }
}

Properties start with a capital letter by convention. Now you can access it as follows:

Checks c = new Checks("hello");
string h = c.Hostname2; // h = "hello"

Andy : , , setter private:

public string Hostname2 { get; private set; }
+7

:

class Checks {

    // this string, declared in the class body but outside
    // methods, is a class variable, and can be accessed by
    // any class method. 
    string _hostname2;

    public Checks(string hostname2) {
        _hostname2 = hostname2;
    }

    public void Testing() {
        MessageBox.Show(_hostname2);
    }

}
+2

You can open a public property to reassign hostname2, which is the standard for exposing your personal variables


class Checks
{
    private string _hostname;
    public Checks(string hostname2)
    {
        _hostname = hostname2;
    }
    public string Hostname 
    {
       get { return _hostname; }
    }
}
+2
source

All Articles