I have been doing my homework for the last few hours. However, I got stuck.
So basically I am trying to assign new value to a string in a Method. This new value must be passed to the method. I tried the following but the test failed. (Please See attached screenshot)
Thank you very much in advance
private string surname;
private string ChangeSurname(ref string surname)
{
this.surname = "New Value";
return surname;
}
Note I tried without ref too but it did not solve the problem. Getting the same error message.
CodePudding user response:
You don't need pass the argument as reference
As you are setting the global value in a private method, the method can be void and not return anything (of course there is no harm in returning it):
private string surname; private void ChangeSurname(string newValue) { this.surname = newValue; }
or if you need to also return it after setting the value (which I doubt that):
private string ChangeSurname(string newValue)
{
this.surname = newValue;
return newValue;
}
CodePudding user response:
String is a reference type & it is immutable. When a reference type variable is passed from one method to another, it doesn't create a new copy; instead, it passes the variable's address. So, If we change the value of a variable in a method, it will also be reflected in the calling method.
public class Name{
public string Surname { get; set; }
}
public void ChangeSurname(Name name2,string NewVal)
{
name2.Surname = NewVal;
}
Now the method ChangeSurname() can be called like as below
Name name1 = new Name();
name1.Surname = "Tiwary";
ChangeSurname(name1,"Sharma");
Output: Surname "Tiwary" will be changed to "Sharma"