Ref and Out Keyword in C#
In today's post i am going to cover "Ref and Out Keyword in C#"?Both ref and out parameters are used to pass arguments within a method.
The ref keyword causes arguments to be passed by reference not by value.It means,any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword.
Below examples will clear the concept of Ref keyword.
Output - 0
Why output is 0, it is because changes has been done to local scope of GetData method.
Now use Ref keyword in same example -
Output - 12
Out
The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. To use an out parameter,
Here is the example of Out keyword -
In the previous tutorials i have explained sealed class ,Abstract class ,Ajax call etc.Here i am going to cover Ref and Out parameter.
RefThe ref keyword causes arguments to be passed by reference not by value.It means,any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword.
Below examples will clear the concept of Ref keyword.
Output - 0
Why output is 0, it is because changes has been done to local scope of GetData method.
Now use Ref keyword in same example -
Output - 12
Out
The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. To use an out parameter,
both the method definition and the calling method must explicitly use the out keyword.
Note: It is not mandatory as out parameter as assigned some value before passing as argument to a method but in case of ref parameter ,it must have assigned value before passing as argument.
Note: It is not mandatory as out parameter as assigned some value before passing as argument to a method but in case of ref parameter ,it must have assigned value before passing as argument.
Here is the example of Out keyword -
Key points to remember
Thanks.
- The ref and out keywords are treated differently at run-time, but they are treated the same at compile time.
- Methods cannot be overloaded if one method takes a ref argument and the other takes an out argument(at compile time both act as identical)
Below example that show how both Ref and Out are treated at compile time.
Hope you enjoyed this post.Please provide your feedback.
Thanks.
Ref and Out Keyword in C#
Reviewed by CodiBucket
on
07:53
Rating:
No comments: