No tiny class, no out parameters.

The problem
A class just to carry two values.
class ClosestResult{ public Enemy Enemy; public float Distance;} // in FindClosest, after the searchreturn new ClosestResult { Enemy = best, Distance = bestDistance };
A whole class, and a new object every call, to get two values out of one method.
The fix
Return a tuple.
A tuple bundles a few values, with names, right in the method's signature. No class to write.
( Enemy enemy, float distance )→one return
The fix in code
Name them, then unpack them.
(Enemy enemy, float distance) FindClosest(){ // ...search... return ( best, bestDistance );} var ( enemy, distance ) = FindClosest();Aim( enemy, distance );
It's a struct, so nothing is allocated. Unpacking gives you two ordinary locals.
Watch out
Tuples are for nearby code.
Past three values, or all across your game, give it a real name.
- Two or three values
- a tuple
- Used everywhere
- a struct or record
- Public API
- name a type
The rule
Two answers? Return a tuple.
- Declare
- (A a, B b) Fn()
- Return
- return ( a, b );
- Unpack
- var ( a, b ) = Fn();