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# wron
Ran across this and thought I should share what Microsoft says:
"Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same. A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference."
MSDN: ref (C# Reference)
You need to learn the difference between reference types and value types. Here I presume you are using a reference type License, which means you are actually parsing a reference to the instance in question.
See: http://msdn.microsoft.com/en-us/library/aa711899(v=vs.71).aspx
Although, not necessarily correct a value type is often allocated on the stack or within a reference type. While reference types are always allocated on the managed heap.
When passing license in InsertLicense you pass it not by value but as reference. That means when changing the registered item to true, it will change that and after returning the reference the registered item will be true.
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:
public static void InsertLicense(ref License license)
{
// Change to the parameter itself, not the object it refers to!
license = null;
}
Now if you call InsertLicense(ref foo)
, it will make foo
null afterwards. Without the ref, it wouldn't.
For more information, see two articles I've written:
You are passing the licence argument by value; essentially this means you can modify any public properties of the object. However, if you reassign the reference of the licence object to a new object, i.e. if you did this:
public static void InsertLicense(License license)
{
license = new Licence();
UpdateLicense(license);
}
the caller won't reference the new license object defined in the static method unless you passed it by ref.
Remember that all parameters are passed into methods by value unless you use the ref or out keywords.