C# .Net Understanding Ref and Out keyword Part 1

ref-cover

Hello.. I ‘m so sorry that i can’t keep my promise to write article every week, it’s because i was little bit busy on few weeks ago, don’t worry.. i realize about that 😀 . And this time, i’m going to explain about two .Net simple keywords, that maybe some of us don’t care about how to use it. Do you remember the data types fundamental  on .Net? Yup, that’s value types and reference types.

Let’s get a flashback about it.

  • Value Types :

Variables that are based on value types directly contain values. Assigning one value type variable to another copies the contained value. This differs from the assignment of reference type variables, which copies a reference to the object but not the object itself. (msdn)For more information you can follow this link.

  • Reference Types :

Variables of reference types store references to the actual data. (msdn)For more information you can follow this link.

You got it? Let’s try the example codes :

This is the output :

ref-1-result

You see that integer is one kind of value types and string is one kind of reference types. But why the result are same? It’s because when passed by value, the pointer is copied, therefore modifying that string doesn’t affect the instance. By default the data types are passed by value except for class object. How to make it passed by reference? We can use ref keyword. What is ref keyword?

The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the called method is reflected in the calling method. For example, if the caller passes a local variable expression or an array element access expression, and the called method replaces the object to which the ref parameter refers, then the caller’s local variable or the array element now refer to the new object. (msdn)For more information you can follow this link.

Update your code with this :

This is the output :

ref-2-result

Now the value is updated, because the pointer is pointing the instance with ref keyword. The main point of this topic is we have to understand the life cycle of variable (parameter passing). Next time i’ll explain the difference between ref and out keyword.

FatkhanFauzi About FatkhanFauzi

A passionate software engineer who wants to share anything that he learns and some of his life experiences. Want to know more about him? see Fatkhan Fauzi Profile


So, what do you think ?

Leave a Reply

%d bloggers like this: