out versus ref
Loading
out versus ref
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Emily FosterRank #3,495 · 415 reputationPosted Jan 17, 2025, 6:05 PM EST
Certainly! In C#, both `out` and `ref` are used for passing arguments to methods by reference rather than by value. The main difference lies in how they are treated within the method:
1. `ref` keyword: When using `ref`, the variable must be initialized before it is passed to the method. This is because the method may read and modify the variable. Changes made to the parameter inside the method will be reflected in the calling code. Here's a basic example:
void ModifyValue(ref int num) { num += 10; } int value = 5; ModifyValue(ref value); Console.WriteLine(value); // Output: 152. `out` keyword: On the other hand, with `out`, the variable can be uninitialized before the method call. The method must explicitly assign a value to the parameter before it returns. This is useful when a method needs to return multiple values. Here's an example:
void GetValues(out int num1, out int num2) { num1 = 10; num2 = 20; } int result1, result2; GetValues(out result1, out result2); Console.WriteLine(result1); // Output: 10 Console.WriteLine(result2); // Output: 20In summary, you can use `ref` when you want to pass a value to a method and also receive updates back from the method, whereas `out` is suitable when a method needs to return multiple values.
Let me know if you have any more questions or if you'd like further clarification!
Tuhin PaulRank #7 · 71.9K reputationPosted Jan 17, 2025, 11:04 PM EST
Part 1:
We will demonstrate the use of
outandrefin different functionalities of the system.outto return additional details about a candidate or when we need to ensure that the method modifies the argument passed.refwhen we need to pass a variable that might be modified or updated within the method and is also expected to have a meaningful value passed in at the start.The system will allow recruiters to add new candidates, update their application status, and fetch details of candidates.
Candidate Class (model layer)
public class Candidate { public int CandidateId { get; set; } public string FullName { get; set; } public string Email { get; set; } public string AppliedPosition { get; set; } public DateTime DateApplied { get; set; } public string Status { get; set; } // Constructor to initialize a new candidate public Candidate(int id, string name, string email, string position) { CandidateId = id; FullName = name; Email = email; AppliedPosition = position; DateApplied = DateTime.Now; Status = "Applied"; // Default status } }Tuhin PaulRank #7 · 71.9K reputationPosted Jan 18, 2025, 12:56 AM EST
Part 2:
CandidateService Class
This class will contain methods for managing candidates, such as adding new candidates, updating statuses, and retrieving candidate details.
using System; using System.Collections.Generic; using System.Linq; public class CandidateService { private List candidates = new List(); private int candidateIdCounter = 1; public void AddCandidate(string name, string email, string phone, string position) { var candidate = new Candidate { CandidateId = candidateIdCounter++, FullName = name, Email = email, Phone = phone, AppliedPosition = position, DateApplied = DateTime.Now, Status = "Applied" }; candidates.Add(candidate); Console.WriteLine("Candidate added successfully!"); } public void UpdateCandidateStatus(ref Candidate candidate, string newStatus) { // Using 'ref' to modify the existing candidate object. candidate.Status = newStatus; Console.WriteLine($"Status of {candidate.FullName} updated to {newStatus}"); } public bool TryGetCandidateById(int candidateId, out Candidate candidate) { // Using 'out' because we need to return the candidate found or null. candidate = candidates.FirstOrDefault(c => c.CandidateId == candidateId); return candidate != null; // Return true if found, otherwise false } public void ListCandidates() { Console.WriteLine("\nList of Candidates:"); foreach (var candidate in candidates) { Console.WriteLine($"{candidate.CandidateId}: {candidate.FullName}, Status: {candidate.Status}"); } } }Tuhin PaulRank #7 · 71.9K reputationPosted Jan 18, 2025, 12:58 AM EST
Part 3
In the main program, users can interact with the system, such as adding new candidates, listing them, and updating their status.
using System; public class Program { static void Main(string[] args) { CandidateService candidateService = new CandidateService(); while (true) { Console.WriteLine("\nApplication Tracking System (ATS)"); Console.WriteLine("1. Add New Candidate"); Console.WriteLine("2. List All Candidates"); Console.WriteLine("3. Update Candidate Status"); Console.WriteLine("4. Exit"); Console.Write("Please select an option: "); var option = Console.ReadLine(); switch (option) { case "1": // Add a New Candidate Console.Write("Enter Full Name: "); string name = Console.ReadLine(); Console.Write("Enter Email: "); string email = Console.ReadLine(); Console.Write("Enter Phone: "); string phone = Console.ReadLine(); Console.Write("Enter Position Applied For: "); string position = Console.ReadLine(); candidateService.AddCandidate(name, email, phone, position); break; case "2": candidateService.ListCandidates(); break; case "3": Console.Write("Enter Candidate ID to update: "); int candidateId = int.Parse(Console.ReadLine()); if (candidateService.TryGetCandidateById(candidateId, out Candidate candidate)) { Console.Write("Enter new status (e.g., Interview Scheduled, Hired, Rejected): "); string status = Console.ReadLine(); candidateService.UpdateCandidateStatus(ref candidate, status); } else { Console.WriteLine("Candidate not found."); } break; case "4": Console.WriteLine("Exiting the system..."); return; default: Console.WriteLine("Invalid option, please try again."); break; } } } }Tuhin PaulRank #7 · 71.9K reputationPosted Jan 18, 2025, 1:00 AM EST
Part 4:
Usage of
out:outkeyword is used in the methodTryGetCandidateById(int candidateId, out Candidate candidate).outparametercandidateis used to return the candidate object. It doesn't need to be initialized before being passed to the method, and the method is responsible for assigning a value to it (ornullif not found).TryGetCandidateByIdmethod checks if a candidate with the given ID exists, and if so, it assigns the candidate to theoutparameter.Usage of
ref:refkeyword is used in the methodUpdateCandidateStatus(ref Candidate candidate, string newStatus).candidateparameter is passed by reference, meaning any changes made to it inside the method will reflect outside the method as well.candidateobject before passing it to the method (in this case, the candidate is fetched viaTryGetCandidateById).Output of the code :
Application Tracking System (ATS) 1. Add New Candidate 2. List All Candidates 3. Update Candidate Status 4. Exit Please select an option: 1 Enter Full Name: John Doe Enter Email: [email protected] Enter Phone: 123-456-7890 Enter Position Applied For: Software Engineer Candidate added successfully! Application Tracking System (ATS) 1. Add New Candidate 2. List All Candidates 3. Update Candidate Status 4. Exit Please select an option: 2 List of Candidates: 1: John Doe, Status: Applied Application Tracking System (ATS) 1. Add New Candidate 2. List All Candidates 3. Update Candidate Status 4. Exit Please select an option: 3 Enter Candidate ID to update: 1 Enter new status (e.g., Interview Scheduled, Hired, Rejected): Interview Scheduled Status of John Doe updated to Interview Scheduledrefis used when you want to modify an existing object or value inside a method, and the object must be initialized before being passed.outis used when a method returns a value via a parameter, and the caller doesn't need to initialize the parameter before passing it.kuldeep sumanRank #6,010 · 279 reputationPosted Jan 20, 2025, 8:51 AM EST
reftells the compiler that the object is initialized before entering the function, whileouttells the compiler that the object will be initialized inside the function.So while
refis two-ways,outis out-only.Matthew Hess114 reputationPosted Jan 21, 2025, 4:36 PM EST
Great question! "out" and "ref" parameters server different purposes.
Understanding "out" Parameters
You use out parameters when you want to pass multuiple values back to a function caller. Out parameters are not the only way to do this. You could also use a tuple or a simple data class. Here is some code that illustrates these three tequniques:
// Example 1: Using out parameters public void GetDateParts1(DateTime date, out int month, out int day out int year) { month = date.Month; day = date.Day; year = date.Year; } // Example 2: Using a tuple public (int Month, int Day, int Year) GetDateParts2(DateTime date) { return (date.Month, date.Day, date.Year); } // Example 3: Using a class public class DateParts { public int Month; public int Day; public int Year; } public DateParts GetDateParts3(DateTime date) { return new DateParts() { Month = date.Month, Day = date.Day, Year = date.Year }; }Of these three methods, I personally prefer tuples (which were introduced in C# 7 in 2017). They are easy and elegant and efficient. I personally find out parameters to be awkward in comparison, but older older code will use them more heavily. I personally think the approach of using a class starts being most appropriate when you are returning more than 3 values. At that point, it is more manageable than individual parameters.
Understanding "ref" Parameters
The purpose of a ref parameters is to change the way a variable is passed to a function. Normally in C#, C# value types (int, double, decimal, datetime, string, bool, etc...) are passed to a function as a copy of the value, not as a pointer back to the original value. In theory, there might be a time when you want your function to be able to modify the original vaue. Here is a bit of code that shows the difference:
public void TestRefVariable() { int x = 10; Normal(x); // x still = 10, local copy is not changed ByRef(ref x); // x now = 25 because it was changed by the function } public void Normal(int x) { x = 25; // this is a local copy of x } public void ByRef(ref int x) { x = 25; // this points to the caller's copy of x }In my experience, use of ref parameters in C# is very rare. I have worked on projects that ran into hundreds of thousands of lines of code and we never once used ref.
Muhammad Imran AnsariRank #326 · 7.6K reputationPosted Jan 22, 2025, 1:30 AM EST
Hello Alan,
They serve similar purposes (allowing a method to modify the value of a parameter), but there are important differences in how they are used:
out: A keyword used to pass a variable to a method without requiring it to be initialized before calling the method. The method must assign a value to the out parameter before it exits.
ref: A keyword used to pass a variable to a method that must be initialized before calling the method. The method may modify the value of the ref parameter.
using System; class Program { static void Main() { // Example of out int result; CalculateSum(5, 3, out result); Console.WriteLine("Sum (using out): " + result); // Output: 8 // Example of ref int number = 4; UpdateValue(ref number); Console.WriteLine("Updated value (using ref): " + number); // Output: 8 } // Using out static void CalculateSum(int a, int b, out int sum) { sum = a + b; } // Using ref static void UpdateValue(ref int value) { value *= 2; } }Both are useful for different scenarios based on whether or not you need the parameter to be pre-initialized.
Happy Coding, Thank you!