Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dictionary for only one entry [duplicate]

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?

like image 952
Janno Avatar asked Dec 08 '25 07:12

Janno


2 Answers

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
like image 150
Shachaf.Gortler Avatar answered Dec 10 '25 01:12

Shachaf.Gortler


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.

like image 35
Scott Hannen Avatar answered Dec 10 '25 01:12

Scott Hannen