I’m trying to find how to add functionality to C# structures, and in a more elegant way than just wrapping them in entirely new classes. An extension method just isn’t as powerful as an override, and most definitely cannot give a struct event firing/handling capabilities either.
The specific problem I’m currently facing however is detecting and reacting to changes in a Vector2 structure’s members. This is only an internal requirement though, so users of my library should be able to use/perceive only Vector2 structures when interacting with it (while still setting off internal events).
Generally, how can I extend C# structures other than by extension methods or encapsulation?
Specifically, how can I extend the Vector2 structure to support event firing/handling?
The only way is to create extension methods or use encapsulation.
As I said previously you can use encapsulation and create a class. So use this code:
Then you can add interfaces, methods and events.
EDIT :
Firstly if you want to mask completely that internally is used a structure of type
Vector2you should rewrite all methods in this way:For more info look here.
Now it’s simple if you want to create an event that is fired when one members changes.
I’d create a costumized EventArgs. Let’s write some code:
Then you can write your own event: