What's the difference between the “ref” and “out” keywords in C#?
What's the difference between the “ref” and “out” keywords in C#?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
13-Jul-2023The
refandoutkeywords in C# are used to pass parameters by reference. However, there are some key differences between the two keywords.refparameters can be initialized before they are passed to the method.outparameters cannot be initialized before they are passed to the method.refparameters can be used to modify the value of the variable that is passed to the method.outparameters can only be used to get the value of the variable that is passed to the method.In other words,
refparameters allow for bi-directional data flow, whileoutparameters only allow for unidirectional data flow.Here is an example of how the
refkeyword can be used:C#
In this example, the
DoSomething()method takes arefparameter callednumber. Therefkeyword tells the compiler that thenumberparameter is a reference to themyNumbervariable. This means that any changes that are made to thenumberparameter in theDoSomething()method will be reflected in themyNumbervariable.Here is an example of how the
outkeyword can be used:C#
In this example, the
DoSomething()method takes anoutparameter callednumber. Theoutkeyword tells the compiler that thenumberparameter is a reference to a new variable that will be created in theDoSomething()method. This means that thenumberparameter cannot be initialized before it is passed to theDoSomething()method. However, thenumberparameter can be used to get the value of the new variable that is created in theDoSomething()method.