Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a value from a C# static method to a label

I have the following static function in c#

public static string Greet(string name)
    {
        string greeting = "welcome  ";

        // is it possible to pass this value to a label outside this static method?
        string concat = string.Concat(greeting, name);

        //error
        Label1.text = concat;

        //I want to return only the name
        return name;
    }

As you can see in the comments, I want to retain only the name as the return value, however I want to be able to take out the value of the concat variable to asign it to a label, but when i try the compiler refuses, can it be done? Is there a work around?

Thank you.

like image 765
tika Avatar asked Feb 05 '10 04:02

tika


2 Answers

If the method must be static for some reason, the main approach here would be to pass any required state into the method - i.e. add a parameter to the method that is either the label or (better) some typed wrapper with a settable property like .Greeting:

public static string Greet(string name, YourType whatever)
{
    string greeting = "welcome  ";

    whatever.Greeting = string.Concat(greeting, name);

    return name;
}

(where YourType could be your control, or could be an interface allowing re-use)

What you don't want to do is use static state or events - very easy to get memory leaks etc that way.


For example:

public static string Greet(string name, IGreetable whatever)
{
    string greeting = "welcome  ";

    whatever.Greeting = string.Concat(greeting, name);

    return name;
}
public interface IGreetable {
    string Greeting {get;set;}
}
public class MyForm : Form, IGreetable {
    // snip some designer code

    public string Greeting {
        get { return helloLabel.Text;}
        set { helloLabel.Text = value;}
    }

    public void SayHello() {
        Greet("Fred", this);
    }
}
like image 114
Marc Gravell Avatar answered Oct 14 '22 23:10

Marc Gravell


Either non-static:

public string Greet(string name)
{
    const string greeting = "welcome  ";
    string concat = string.Concat(greeting, name);
    Label1.Text = concat;
    return name;
}

Or still static passing the label like Greet("John", Label1):

public static string Greet(string name, Label label)
{
    const string greeting = "welcome  ";
    string concat = string.Concat(greeting, name);
    label.Text = concat;
    return name;
}

But not sure why you need to return the name in either case...if you had it when calling the function, you already have it in the scope you'd be returning to. Example:

var name = "John";
Greet(name);
//can still call name here directly
like image 31
Nick Craver Avatar answered Oct 14 '22 23:10

Nick Craver