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
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; }
                        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);
    }
}
                        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; }
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With