1

It is possible to write one method that can set value to different variables which are loaded by parameter?

I think something about like this:

void SetBooleanValue(bool myVariable, bool newValue)
{
    myVariable = newValue;
}

and then use this like that:

bool isConnected = false;
bool isFinished = true;

public ClassConstructor()
{
    SetBooleanValue(isConnected, true);
    SetBooleanValue(isFinished, false);
}

The problem is my method only gets value of isConnected and isFinished and can't modify original values of those variables.

How to get reference to them?

5
  • 1
    Why is this tagged Java? Oct 30, 2017 at 14:17
  • 4
    That´s what the ref-keyword is for. Oct 30, 2017 at 14:17
  • @JuanCarlosMendoza sorry for Java tag but i think it will work in java and c# the same way
    – mmm
    Oct 30, 2017 at 14:20
  • 1
    @MadMike6661 It will not work in Java because Java doesn't have the possibility to pass a value type by "ref". You would need to "box" that value into some kind of object. Oct 30, 2017 at 14:22
  • 2
    While your question makes sense in java and c#, solutions look very different, as the ref-keyowrd from C# doesn´t exist in Java. Oct 30, 2017 at 14:22

1 Answer 1

2

That´s what the ref-keyword is for:

void SetBooleanValue(ref bool myVariable, bool newValue)
{
    myVariable = newValue;
}

Use it like this:

SetBooleanValue(ref isConnected, true);

This keyword enables you to set the provided instance to something different.

Not the answer you're looking for? Browse other questions tagged or ask your own question.