-
Notifications
You must be signed in to change notification settings - Fork 8
C# Tips
Valk edited this page Oct 8, 2024
·
6 revisions
There are 2 ways to approach this.
- Create a new class that holds the members
- Add out params as needed for the additional members
If you don't want to create a whole new class the latter may be what you are looking for.
You may have something like public event Action<int, int, int> OnPlayerUpdate
. There are a few things wrong with this.
- Assuming this is defined in player class this should not need to have "Player" defined in its name.
- The single responsibility principle (SRP) is being violated. There should be separate events like
OnHealthChanged<int>
andOnPositionChanged<Vector2>
. - But the biggest problem is the event args are implicit. You have no idea what they mean on the subscribers end. If we ignore SRP, we will need to create a
PlayerUpdateEventArgs
class with a primary constructor containing all the event args as public properties. Then we can pass this class as a single param and our subscriber will know what's what.
Too much text together can blind your eyes.
Before
ItemContainer targetItemContainer = otherInventoryContainer.ItemContainers[otherIndex];
TransferEventArgs args = new(areSameType, index, targetItemContainer);
OnPreTransfer?.Invoke(args);
After
ItemContainer targetItemContainer = otherInventoryContainer.ItemContainers[otherIndex];
TransferEventArgs args = new(areSameType, index, targetItemContainer);
OnPreTransfer?.Invoke(args);