Skip to main content
gamedev.net
🔒 Locked

[.net] C#, passing by reference

Started by Endar Jan 29, 2007 at 11:15 PM 1 replies 750+ views
Original Post
Endar
Endar

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
Agony
Agony
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 nly, and not for things themselves." - John Locke o
yaroslavd
yaroslavd
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);}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.