[.net] C#, passing by reference

Started by
1 comment, last by yaroslavd 17 years, 2 months ago

public void function(ref int i)
{
    // code
}


public void other_function()
{
    int i = new int(5);

    function(ref i);
}
That's right? So, I understand the 'ref' in the 'function' parameter list, but what about the 'ref' in the function call? Why does that need to be there? I've looked at a couple of sites, and MSDN, but the only things about it that I've seen is that it needs to be there. Not why.
[size="2"][size=2]Mort, Duke of Sto Helit: NON TIMETIS MESSOR -- Don't Fear The Reaper
Advertisement
I believe its primary (if not only) purpose is to make it very clear to the caller that the function will likely change the variable. There have been many bugs in programs caused by programmers assuming that a parameter was passed by value, when it was really passed by reference. This disallows such a mistake.
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke
I'm pretty sure you can overload the function to support a ref and a non-ref argument. So like this:
public void function(ref int i){    // code}public void function(int i){    // code}public void other_function(){    int i = 5;    function(ref i);    function(i);}

This topic is closed to new replies.

Advertisement