out/ref keyword has been used to return more than one values from a function.
ref keywords need to be defined before you can pass them as a parameter to function but on the other hand out variables need not be initialized before they can be passed as a parameter to a function.
In case of ref, the called method is not bound to assign any value to the ref parameter since it has already been initialized by calling method but in case of out, the called method has the responsibility of assigning value of out parameter failing which results in a compile time error.
Problem with the out keyword in past was that we need to declare out Parameter before it can be passed as argument
Before C# 7.0
Usage of out parameter
int outParameter; InitializeValue(out outParameter); Console.WriteLine("Value of outParameter is {0}", outParameter);
As you can see variable need to be declared only and not initialized before passing it as parameter to function. There is no restriction as such by compiler, regarding assignment of out parameter in calling functions but there is no point assigning values since that must be overwritten by called method.
int outParameter = -1; InitializeValue(out outParameter); //Will be overwritten here in any case Console.WriteLine("Value of outParameter is {0}", outParameter);
With C# 7.0 you can now declare out variable as close to usage as possible i.e. while passing it as arguments
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-5021110436373536"
data-ad-slot="9215486331">
C# 7.0 Enhancements
//out can be declared inside the agument
InitializeValue(out int outParameter); Console.WriteLine("Value of outParameter is {0}", outParameter);
// One common scenario where this feature can become handy is
string someNumberBoxedIntoString = "23"; if (int.TryParse(someNumberBoxedIntoString, out int someValue)) { //If value is parsed used here someValue = 0; } var someValueAssigment = someValue; //You can still use the variable here.
All code samples are available at my GitHub profile
I am a corporate trainer and solution architect and have a great team of software professionals. Please contact in case you need our services by sending email to contact@techprocompsoft.com. Here is our company website .