I read the C++ version of this question but didn't really understand it.
Can someone please explain clearly if it can be done and how?
I read the C++ version of this question but didn't really understand it.
Can someone please explain clearly if it can be done and how?
Use .NET 4.0+'s Tuple:
For Example:
Tuples with two values have
Item1
andItem2
as properties.You can use three different ways
1. ref / out parameters
using ref:
using out:
2. struct / class
using struct:
using class:
3. Tuple
Tuple class
C# 7 Tuples
There are several ways to do this. You can use
ref
parameters:This passes a reference to the function thereby allowing the function to modify the object in the calling code's stack. While this is not technically a "returned" value it is a way to have a function do something similar. In the code above the function would return an
int
and (potentially) modifybar
.Another similar approach is to use an
out
parameter. Anout
parameter is identical to aref
parameter with an additional, compiler enforced rule. This rule is that if you pass anout
parameter into a function, that function is required to set its value prior to returning. Besides that rule, anout
parameter works just like aref
parameter.The final approach (and the best in most cases) is to create a type that encapsulates both values and allow the function to return that:
This final approach is simpler and easier to read and understand.
You could use a dynamic object. I think it has better readability than Tuple.
You cannot do this in C#. What you can do is have a
Using out parameter Using custom class (or struct)out
parameter or return your own class (or struct if you want it to be immutable).From this article, you can use three options as posts above said.
KeyValuePair is quickest way.
out is at the second.
Tuple is the slowest.
Anyway, this is depend on what is the best for your scenario.