Friendlycoder

Hi there

is using ref the only was to pass a value to a method, changing the value and return the value back to the calling method with its new value




Re: Visual C# General Passing parameters

CalvinR

Yes it is, but you could also return it from the method (though that's probably stating the obvious.)





Re: Visual C# General Passing parameters

Friendlycoder

I tried to return it like this, but the complier was not happy.

static void Main()

{

int i = 0;

i = addpenalty(i);

Console.WriteLine("i before = " + i);

}

int addpenalty(int i)

{

i = i + 1;

Console.WriteLine("i inline = " + i);

}






Re: Visual C# General Passing parameters

TilakGopi

Hi,

int addpenalty(int i)

{

i = i + 1;

Console.WriteLine("i inline = " + i);

}

U didn't return the value of i from the function, add 'return i' in the function , then it works fine.It should be like..

int addpenalty(int i)

{

i = i + 1;

Console.WriteLine("i inline = " + i);

return i;

}

Hope u got the error in ur code.

Thanx,

Ch.T.Gopi Kumar.






Re: Visual C# General Passing parameters

Friendlycoder

Thank you Just worked out, the method needs to be static correct

One more questions, how does this benefit from being non REF, as it does the same things functionality wise.

 






Re: Visual C# General Passing parameters

TilakGopi

Hi,

I feel using ref parametes beneficial than returning values,since in that way u can get more values get assigned new values,but we can return only one value.

Thanx,

Ch.T.Gopi Kumar.






Re: Visual C# General Passing parameters

ShellShock

It is generally preferable to explicitly return a value rather than use ref parameters. If you use ref parameters, the danger is you just keep adding more and more to the same method, until it has loads of parameters. This is poor design and makes your code hard to understand.

Instead you should be creating a type (class) that encapsulates all the information you want to return, and return a new instance of that class.





Re: Visual C# General Passing parameters

Friendlycoder

Great, thanks for your answers.