Saturday, February 5, 2011

.NET Interview question 4 :- What is difference between out and ref in c#?

.NET Interview question 4 :- What is difference between out and ref in c#?


This is a great .NET Interview question and also very very confusing question. By default parameters are always passed by value to methods and functions.If you want to pass data byref then you can use either out or ref keyword.
There are two big difference between these keywords one is the way data is passed between the caller code and method and second who is responsible for initialization.

Way the data is passed(directional or bi-directional)
==============================================================

When you use OUT data is passed only one way i.e from the method to the caller code.

When you use REF , Data can be passed from the called to the method and also vice versa.

Who initializes data
==============================================================
In OUT the variables value has to be intialized in the method. In REF the value is initialized outside the method by the caller.


The most important thing the interviewer will like to hear from you
When to use when

==============================================================

OUT will be used when you want data to be passed only from the method to the caller.

REF will be used when you want data to be passed from the called to the method and also vice versa.


Click here to view 22 top .net interview questions

No comments: