• Advertisement
Sign in to follow this  

[.net] C#, passing by reference

This topic is 4040 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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);
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement