I have a function which parses one string into two strings. In C# I would declare it like this:
void ParseQuery(string toParse, out string search, out string sort) { ... }
and I'd call it like this:
string searchOutput, sortOutput; ParseQuery(userInput, out searchOutput, out sortOutput);
The current project has to be done in C++/CLI. I've tried
using System::Runtime::InteropServices; ... void ParseQuery(String ^ toParse, [Out] String^ search, [Out] String^ sort) { ... }
but if I call it like this:
String ^ searchOutput, ^ sortOutput; ParseQuery(userInput, [Out] searchOutput, [Out] sortOutput);
I get a compiler error, and if I call it like this:
String ^ searchOutput, ^ sortOutput; ParseQuery(userInput, searchOutput, sortOutput);
then I get an error at runtime. How should I declare and call my function?
For using out keyword as a parameter both the method definition and calling method must use the out keyword explicitly. The out parameters are not allowed to use in asynchronous methods. The out parameters are not allowed to use in iterator methods. There can be more than one out parameter in a method.
Calling a method with an out argument In C# 6 and earlier, you must declare a variable in a separate statement before you pass it as an out argument. The following example declares a variable named number before it is passed to the Int32. TryParse method, which attempts to convert a string to a number.
The out parameter in C# is used to pass arguments to methods by reference. It differs from the ref keyword in that it does not require parameter variables to be initialized before they are passed to a method. The out keyword must be explicitly declared in the method's definition as well as in the calling method.
C# provides out keyword to pass arguments as out-type. It is like reference-type, except that it does not require variable to initialize before passing. We must use out keyword to pass argument as out-type. It is useful when we want a function to return multiple values.
C++/CLI itself doesn't support a real 'out' argument, but you can mark a reference as an out argument to make other languages see it as a real out argument.
You can do this for reference types as:
void ReturnString([Out] String^% value) { value = "Returned via out parameter"; } // Called as String^ result; ReturnString(result);
And for value types as:
void ReturnInt([Out] int% value) { value = 32; } // Called as int result; ReturnInt(result);
The % makes it a 'ref' parameter and the OutAttribute marks that it is only used for output values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With