2

I need to return 2 values (a string and a point) from a method and I dont really want to use ref/out as the values should stay together.

I was thinking of using a Dictionary<string, Point>.

My question is: Is dictionary a good choice of data structure if it only has one KeyValuePair? Or are there any other suitable options?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Janno
  • 149
  • 1
  • 3
  • 13

4 Answers4

5

If you dont want to create a named class , you can use Tuple to return more than one parameter

Tuple<int,  Point> tuple =
        new Tuple<int,  Point>(1, new Point());

return tuple
Shachaf.Gortler
  • 5,655
  • 14
  • 43
  • 71
4

You can create your own class. But Tuple<T1, T2> may be convenient. It's just for that sort of thing, when you need to pass around an object containing a few different types.

I'd lean toward creating a class unless it's extremely clear what the tuple is for just by the definition. That way you can give it a name that improves readability. And it can also save a maintenance nuisance if you later determine that there are more than two values. You can just maintain one class instead of replacing Tuple<int, Point> with Tuple<int, Point, Something> in multiple places.

I wouldn't use KeyValuePair because someone looking at it would reasonably assume that there's a dictionary somewhere in the picture, so it would create some confusion. If there are just two values and no dictionary then there is no key.

Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
2

I'd use a Class or a Structure to store both values. I prefer it to maintain the code and allow you to extend the system in the future.

public class MyData {
    public string MyString {get;set;}
    public Point MyPoint {get;set;}
}

public class Storage {
    public MyData retrieveMyData() {
        MyData data = new MyData();
        return data;
    }
}
Valdek Santana
  • 337
  • 1
  • 8
1

Whenever you see this you should pause and think "Should this be an object?" If it's a one off you can use Tuple but most times you'll come up with a situation where the same parameters are used in conjunction again. By that point you'll wish that you had created an object the first time.

By creating a object for the set of parameters you can give it a name which will increase readability. If you encapsulate the parameters into properties of an object you can also create getter and setter methods, which will allow you to further control access to them and add more functionality if the need comes up in the future.

The main thing is readability. I might call it a NamedPoint which tells anyone reading my code why I've paired the string and the point together. I could later add validation to the name if I wanted it to be a certain length or not start with a number or any number of other things.

Patrick Graham
  • 972
  • 8
  • 18