What is the difference between out and ref parameters in .NET?

Both ref and out parameters are used to return multiple values from a method. They are used for the same purpose but the only difference is that: ref parameters have to be initialized before being passed as the method parameter but the out parameters need not be initialized.



Here is an example to demonstrate it:

class sampleClass {
int sampleMember1, sampleMember2;
public sampleClass(int value1, int value2) {
sampleMember1= value1;
sampleMember2= value2;
}
public void getValues(out int value1, ref int value2) {
value1 = sampleMember1;
value2 = sampleMember2;
}
public static void Main() {
sampleClass obj = new sampleClass(200,400);
int value1;
int value2=0;
obj.getValues(out value1, ref value2);
Console.WriteLine("The Values are: {0}, {1}", value1, value2);
}
}

Output of this code will be: The Values are: 200, 400

Note that in this example the out parameter value1 is not initialized and the ref parameter value2 is initialized to 0 before passing it to getValues method.

| Can you call a constructor from another constructor of the Class in .NET? | Difference between Response.Output.Write() method and Response.Write() method in .NET | How do you establish multiple inheritance in C#? | How do you introduce a ReadOnly property in C#? | How do you perform constructor overloading in C#? | Is catch(Exception) recommended to be used in .NET? | What are the different access modifiers available in C#? | What are the different ways of overloading in C#? | What are the members of stringbuilder class in C#? | What is Multicast Delegate? Explain it with example in C# | What is the difference between abstract class and interface in .NET? | What is the difference between Clone and CopyTo methods in .NET | What is the difference between const and readonly in .NET | What is the difference between directcast and ctype in .NET? | What is the difference between out and ref parameters in .NET | What is the difference between public assembly and private assembly in .NET | What is the difference between strong typing and weak typing in .NET? | What is the difference between Trace and Debug in .NET | What is the need for Abstract Factory Pattern in C#? | What is the need for Adapter Pattern in C# |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.