Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using strings from other classes C#

Tags:

c#

.net

I have a class that requests that when called a string is sent when requesting / initializing it.

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

    }

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

How would it be possible to take the string "hostname2") in the class constructor and allow this string to be called anywhere in the "Checks" class?

E.g. I call Checks(hostname2) from the Form1 class, now when the Checks class is initialized I can then use the hostname2 string in my Checks class as well

like image 340
James Teare Avatar asked Jan 14 '12 13:01

James Teare


3 Answers

Declare a member inside the class and assign the value 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 to have outside access, make it a 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 like this:

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

Thanks to Andy for pointing this out: if you want the property to be read-only, make the setter private:

public string Hostname2 { get; private set; }
like image 148
Tudor Avatar answered Oct 13 '22 11:10

Tudor


You need to copy the constructor argument in a class variable:

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);
    }

}
like image 38
Paolo Tedesco Avatar answered Oct 13 '22 09:10

Paolo Tedesco


You can expose a public property to retun the hostname2 value which is the standard for exposing your private varibles


class Checks
{
    private string _hostname;
    public Checks(string hostname2)
    {
        _hostname = hostname2;
    }
    public string Hostname 
    {
       get { return _hostname; }
    }
}
like image 25
Ehsan Avatar answered Oct 13 '22 11:10

Ehsan