[Solved] C# arguments values in methods [closed]


Here are three versions of your code to demonstrate what is going on, and what I think you’re really asking:

Original:

private void button1_Click(object sender, EventArgs e)
{
    // Set c to 100
    int c=100;

    // Print the result of Count, which (see below) is ALWAYS 115.
    MessageBox.Show(Count(c).ToString());
}

public int Count(int a)
{
    // Set a to 115 (there is no add here, I think this is a typo)
    a=115;
    // Return a, which is ALWAYS 115.
    return a;
}

What I think you meant:

private void button1_Click(object sender, EventArgs e)
{
    // Set c to 100
    int c=100;

    // Print the result of Count, which will be 215.
    MessageBox.Show(Count(c).ToString());
}

public int Count(int a)
{
    // Add 115 to a.
    a+=115;

    // Return the result (if a == 100, this will return 215)
    return a;
}

What I think you’re getting at:

private void button1_Click(object sender, EventArgs e)
{
    // Set c to 100
    int c=100;

    // Call the count function, passing in a reference for c.
    Count(ref c);

    // Print the value of c. This will be 215 because the Count function set c to a new value.
    MessageBox.Show(c.ToString());
}

public void Count(ref int a)
{
    a+=115;
}

In this last case, I changed the function to public void Count(ref int a). The ref modifier allows the function to assign a new value using a reference to another variable. Normally, parameters are “by value”, where a copy of the variable’s value is passed in.

Note that the second version would be preferred in this case. By reference parameters should only be used when they are truly necessary, not as a replacement for a simple return value.

1

solved C# arguments values in methods [closed]