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.
[.net] C#, passing by reference
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.
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
Popular Topics
Advertisement