0

I want to pass a field reference to my method while an event is fired, but the reference is not passed because my field has the same value.

Here is my code:

private uint _myNumberField;

private void TextBox_OnTextChanged(object sender, TextChangedEventArgs e)
{ 
    HandleTextBoxChanged(sender, _myNumberField);
}

private void HandleTextBoxChanged(object textBoxObject, uint myNumber)
{
    var textBox = textBoxObject as TextBox;

    if (textBox == null)
        return;

    myNumber = 123;
}

After firing the TextBox_OnTextChanged event the field _myNumberField should have the value 123 but has the value 0.

2 Answers2

2

You need to provide myInt as reference, not as value, which is done using the ref-keyword on your delegate:

delegate void HandleTextBoxChanged(object, ref uint);

But wouldn´t it be better to directly update _myNumberField within HandleTextBoxChanged in the first place?

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
1

Use the ref keyword:

private uint _myNumberField;

private void TextBox_OnTextChanged(object sender, TextChangedEventArgs e)
{ 
    HandleTextBoxChanged(sender, ref _myNumberField);
}

private void HandleTextBoxChanged(object textBoxObject, ref uint myNumber)
{
    var textBox = textBoxObject as TextBox;

    if (textBox == null)
        return;

    myNumber = 123;
}

Make sure to use ref on the caller as well, before specifying the name of the field. For more information on how to use ref, see this document.

Like others already said, this is not the best approach. But to answer your question, in C# you need to use ref when you are dealing with value types and want to pass by reference.

Nahuel Prieto
  • 371
  • 3
  • 15