Q:

What is the difference between ref & out parameters in c#?

0

What is the difference between ref & out parameters?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Both ref and out are used to pass the arguments in the function. The main difference between ref and out is that a variable you pass as an out parameter doesn’t need to be initialized but passing it as a ref parameter it has to be set to something.

Example,

int a;
Test(out a); // OK
int b;
Test(ref b); // Error: b should be initialized before calling the method

There are some differences between a ref and an out that I have arranged in a table for easier comparison:

REF KEYWORD OUT KEYWORD
The parameters must initialize before it passes to ref. It is not necessary to initialize parameters before it passes to out.
It is not necessary to initialize the value of a parameter before returning to the calling method. It is necessary to initialize the value of a parameter before returning to the calling method.
The passing of value through the ref parameter is useful when the called method also needs to change the value of the passed parameter. The declaring of parameter throughout parameter is useful when a method returns multiple values.
When the ref keyword is used the data may pass in bi-directional. When out keyword is used the data only passed in unidirectional.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Interview Questions and Answers,You Need To Know

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
What is the difference between var and dynamic in ... >>
<< What do you understand by regular expressions in C...