What is difference between out and ref in c#?

 Posted by Questpond on 2/5/2011 | Category: .NET Framework Interview questions | Views: 11793 | Points: 40
Answer:

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.

My 100 .NET Interview questions http://www.questpond.com


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Pradsir on: 2/6/2011 | Points: 10
We can Say like this ..

Pass by Value --> Read only operation on the passed variable
Pass by Ref --> Read & Write operation on the passed variable

Out Parameter --> Write only operation on the passed variable.

Thanks
Posted by: Questpond on: 2/6/2011 | Points: 10
Hello Pard thats more simple but need modification
Pass by Ref --> Caller and the method can do Read & Write operation on the passed variable

Out Parameter --> Only Method can do Read and Write operation on the passed variable while the caller can only read it.

My 100 .NET Interview questions http://www.questpond.com

Login to post response