Return KeyValuePair or use a variable in C #?

I have a function that should return two rows. I looked at two different ways to do this:

string first = "this is first"; string second = "this is second"; KeyValuePair<string, string> ReturnPair() { return new KeyValuePair<string, string>(first, second); } string ReturnOne(out string other) { other = second; return first; } 

I would like to use the KeyValuePair <> approach, but I feel that I am misusing the purpose for which this object was created.

My questions:

  • Is there a better way to return 2 rows in this example?
  • Is there something wrong with returning KeyValuePair?
+6
c #
source share
6 answers

While KeyValuePair returns nothing technically wrong, the thing you return is conceptually not a key-value. This is a simple couple.

Alternatively, you can use Tuple , which is available in .NET 4.0, or in the meantime, declare your own structure .

I usually recommend out options for returned tuples. Specially, when you use LINQ and functional language constructors, working with out parameters is tedious.

+20
source share

If the data is logically connected to each other, but one of them is not logically the key of the other, I would define a new type that encapsulates it.

If one of the keys to the other, I would use NameValuePair.

+6
source share

This will be my preferred method. KeyValuePair is so detailed.

 String[] ReturnPair() { return new [] { first, second }; } 
+6
source share

My personal opinion would be

 void ReturnTwo(out string one, out string two) { // do assignments } 

I feel this makes it more explicit regarding return values.

+3
source share

I am not a fan of several weekend parmas. I also dislike using a pair of key values โ€‹โ€‹if the first line is not really a key. My suggestion would be to return a List <string> . This will provide a flexible and stable signature. For example, if you later decide that you want to return 3 or 4 lines, you can simply update the logic inside the method without a monkey with a signature.

+1
source share

There is a similar question with many answers: How to return two values โ€‹โ€‹from one method?

From a โ€œclean codeโ€ point of view, using the โ€œoutโ€ parameters to return these two lines is bad. Assuming you donโ€™t have time to reorganize / clean your design, the solution proposed by John Kraft is certainly acceptable.

0
source share

All Articles