C# Methods, Part 2
(Page 1 of 5 )
In this article we will continue our discussion of C# methods, especially passing parameters by value and by reference, and we will also discuss the out and ref keywords. We will end the article with a discussion covering how to create variable parameters methods. An understanding of .NET Types is essential to understanding important parts of this tutorial, so you should read the previous articles (of the series) in order to get the most out of this work.
When you call a method, your code must provide values for the method's parameters. By default, the method creates its copy of the arguments, so you will have two separate copies (the argument and the parameter). This process is called pass by-value, and it's the default in C#.The behavior will differ depending on the passed type, so if you are passing a Value-Type (in this case the value itself will be copied to the method) then the changes made in the parameter value (the one inside the method) will not affect the argument value, because it's a separate copy.
If the passed type is a Reference-Type (in this case the reference itself will be copied, not the object's properties and methods, because it's a copy by value), then you will have two references to the same object, and you can change a property value of the object because you have a reference to it.
There is another parameter vs. argument copying behavior called copy by reference. Again, it differs from Value-Types to Reference-Types, and you have to use the parameter modifier keywords out or ref, as we will discuss soon. For now, when you pass a value type by reference, a reference to the value-type will be passed, and changes made inside the method will be reflected to the argument value. When you pass a Reference-Type, it will pass a reference to the Reference that refers to the object; in other words, it's a double reference.
So we have four cases here: passing Value-Types by value, passing Value-Types by reference, passing Reference-Types by value and passing Reference-Types by reference. Reading this article will help you to establish a good foundation in C# programming techniques.
Next: Handling Value-Type Parameters >>
More C# Articles
More By Michael Youssef