C#: Passing By Reference

Even if you know Object Oriented Programming in certain languages like Java, learning C# is totally different. One of the features that varies greatly in C# from Java is passing values by reference as parameters of methods. In Java, data types are automatically passed by value while classes are passed by reference. Good thing I decided to read out a beginner’s book for C#.

In C#, if you want to pass objects by reference, you would have to use the keyword ref. Take for example the sample code below

If you would call the method change() like this

the output for the object str would be haha instead of hoho. You would have to use the ref keyword for this to work

Data types are a different story. To do the same way to data types as parameters in methods, you would use the out keyword like this

Calling the change method

will output 10 as the value. If you do not use the out keyword, the value of i will still be 1.

Related Posts Plugin for WordPress, Blogger...

4 comments

  1. In this case, actually the string is the mutable class, once it is initialized it cannot be modified. And I found some useful link here: Here.

    Class is always send by reference. But the use of ref will be the special case in some coding style.

    What’s others say?

Leave a Reply

Your email address will not be published. Required fields are marked *