What's the difference between the “ref” and “out” keywords in C#?
What's the difference between the “ref” and “out” keywords in C#?
30712-Jul-2023
Updated on 13-Jul-2023
Home / DeveloperSection / Forums / What's the difference between the “ref” and “out” keywords in C#?
What's the difference between the “ref” and “out” keywords in C#?
Aryan Kumar
13-Jul-2023The
ref
andout
keywords in C# are used to pass parameters by reference. However, there are some key differences between the two keywords.ref
parameters can be initialized before they are passed to the method.out
parameters cannot be initialized before they are passed to the method.ref
parameters can be used to modify the value of the variable that is passed to the method.out
parameters can only be used to get the value of the variable that is passed to the method.In other words,
ref
parameters allow for bi-directional data flow, whileout
parameters only allow for unidirectional data flow.Here is an example of how the
ref
keyword can be used:C#
In this example, the
DoSomething()
method takes aref
parameter callednumber
. Theref
keyword tells the compiler that thenumber
parameter is a reference to themyNumber
variable. This means that any changes that are made to thenumber
parameter in theDoSomething()
method will be reflected in themyNumber
variable.Here is an example of how the
out
keyword can be used:C#
In this example, the
DoSomething()
method takes anout
parameter callednumber
. Theout
keyword tells the compiler that thenumber
parameter is a reference to a new variable that will be created in theDoSomething()
method. This means that thenumber
parameter cannot be initialized before it is passed to theDoSomething()
method. However, thenumber
parameter can be used to get the value of the new variable that is created in theDoSomething()
method.