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 save only the name as the return value, however I want to remove the value of the concat variable in order to assign it to the label, but when I try the compiler refuses, can this be done? Is there any work around?

Thanks.

+5
source share
4 answers

- , - , , () .Greeting:

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

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

    return name;
}

( YourType , )

, , - .. .


:

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

:

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

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

, ... , , . :

var name = "John";
Greet(name);
//can still call name here directly
+4

The problem is that you are trying to instantiate a class variable from a static method.

0
source

Perhaps I am missing the point, but you could not just do:

public static string Greet(string name)
{
    return string.Concat("Welcome ", name);
}

Then use it like:

string name = "John";
label1.Text = Greet(name);

Web methods do not have to be static.

0
source

All Articles