Pass Textbox to Textbox.Text

I currently have something that I want to pass textbox.text to by reference. I do not want to pass the entire text field, and I want the function to change the text along with the return of another variable.

    public int function(int a, int b, string text)
    {
        //do something

        if (a + b > 50)
        {
            text = "Omg its bigger than 50!";
        }

        return (a + b);
    }

Is there a way to pass Textbox.text by ref and change it inside the function?

+3
source share
5 answers

You cannot pass a property by reference to ref, only a field or a variable.

From MSDN :

Properties are not variables. They are actually methods and therefore cannot be passed as ref parameters.

You should use an intermediate variable:

string tmp = textBox.Text;
int x = function(1, 2, ref tmp);
textBox.Text = tmp;
+6
source

, "" ? public int function(int a, int b, TextBox textBox), , , , . public int function(int a, int b, ref string text), textBox.Text, Text, .

+2

? ref... :

public int function(int a, int b, TextBox textb)
{
    //do something

    if (a + b > 50)
    {
        textb.text = "Omg its bigger than 50!";
    }

    return (a + b);
}
+1

. .Text , :

void foo()
{
    string temp = MyTextBox.Text;
    int result = refFunction(ref temp);
    MyTextBox.Text = temp;
}

int refFunction(ref string text)
{ ... }
+1

I assume that the problem is that you are trying to pass TextBox.Textin the second parameter of your function (provided that you change it to take a string by reference). It is true to pass strings by reference, however properties cannot be passed by reference. The best you can do is assign the text to another line, pass this, and then add the text to the text block again:

public int function(int a, int b, ref string text)
{
    //do something

    if (a + b > 50)
    {
        text = "Omg its bigger than 50!";
    }

    return (a + b);
}

string text = TextBox.Text;
function(ref text);
TextBox.Text = text;
0
source

Source: https://habr.com/ru/post/1727790/


All Articles