No, properties that are passed into methods are not modified in that method, because you cannot pass them by reference. Properties are always passed by value, so you cannot change their value within the methods that you pass them two.
However, that's not actually what you are doing in both methods, and that's why one works and one does not.
Your first method:
public void ChangeCountry(string _Country)
{
_Country = "US";
}
attempts to change the value of the parameter that does not have the ref
keyword, which fails (as you noted).
Your second method,
public void ChangeAddress(Address _adr)
{
_adr.Country = "US";
}
is not trying to change the value of its parameter. The Address
object that you pass into the method remains the same instance of Address
for the entire method. However, because Address
is a reference type, you can change its properties, and those changes will persist once the method returns. They will also be visible to any other places that have a reference to the same instance.
To see the difference, if you had tried to do this in your second method, it would have failed, for the same reason your first method does:
public void ChangeAddress(Address _adr)
{
_adr = new Address();
_adr.Country = "US";
}
Here, you are trying to change the value of the parameter -- to a new instance of the class -- and that doesn't work without the ref
keyword.