I know the default is ByVal in C#. I used same variable names in many places and then I noticed passed values change and come back. I think I knew scope mechanism of C# wrong. Here public license overrides the local license values. I know I can easily rename the variable names in conflict but I would like to learn the facts about scope.
public static class LicenseWorks
{
public static void InsertLicense(License license)
{
license.registered = true;
UpdateLicense(license);
}
}
public partial class formMain : Form
{
License license;
private void btnPay_Click(object sender, EventArgs e)
{
license.registered = false;
LicenseWorks.InsertLicense(license);
bool registered = license.registered; //Returns true!
}
}
Update: I’ve added below as solution:
public static void InsertLicense(License license)
{
license = license.Clone();
...
}
The argument is being passed by value – but the argument isn’t an object, it’s a reference. That reference is being passed by value, but any changes made to the object via that reference will still be seen by the caller.
This is very different to real pass by reference, where changes to the parameter itself such as this:
Now if you call
InsertLicense(ref foo), it will makefoonull afterwards. Without the ref, it wouldn’t.For more information, see two articles I’ve written: