- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between out and ref keyword in C#
out keyword
out keyword is used to pass arguments to method as a reference type and is primary used when a method has to return multiple values. ref keyword is also used to pass arguments to method as reference type and is used when existing variable is to be modified in a method. Following is the valid usage of ref and out keywords in C#.
Example
using System.IO; using System; public class Program { public static void update(out int a){ a = 10; } public static void change(ref int d){ d = 11; } public static void Main() { int b; int c = 9; Program p1 = new Program(); update(out b); change(ref c); Console.WriteLine("Updated value is: {0}", b); Console.WriteLine("Changed value is: {0}", c); } }
Output
Updated value is: 10 Changed value is: 11
Following are some of the important differences between ref and out keywords.
Sr. No. | Key | ref keyword | out keyword |
---|---|---|---|
1 | Purpose | ref keyword is used when a called method has to update the passed parameter. | out keyword is used when a called method has to update multiple parameter passed. |
2 | Direction | ref keyword is used to pass data in bi-directional way. | out keyword is used to get data in uni-directional way. |
3 | Initialization | Before passing a variable as ref, it is required to be initialized otherwise compiler will throw error. | No need to initialize variable if out keyword is used. |
4 | Initialization | In called method, it is not required to initialize the parameter passed as ref. | In called method, it is required to initialize the parameter passed as out. |
Advertisements