I just have a small question regarding instance variable placements.
Example:
private void example_MouseMove(object sender, MouseEventArgs e){
//do stuff
}
A mouse move event in c# polls all the time. Sometimes I might want to only run the code inside it when the mouse position fully moves to another pixel. So I would write this:
private void example_MouseMove(object sender, MouseEventArgs e){
if (_prevMousePosition == Cursor.Position) return;
//Do stuff
}
My question is this: Does the variable "_prevMousePosition" go at the top of the class as per usual, or does it sit directly on top of the method, like so:
private Point _prevMousePosition = new Point(0, 0);
private void example_MouseMove(object sender, MouseEventArgs e){
if (_prevMousePosition == Cursor.Position) return;
//Do stuff
}
I feel like it should sit on top of the method since the only place it will be accessed is the event, and it's only purpose outside of the method is to retain the previous mouse position.
Also, if there's another way to achieve the same functionality without the instance variable, I'd love to know it.
My question is this: Does the variable "_prevMousePosition" go at the top of the class as per usual, or does it sit directly on top of the method, like so:
This is purely a personal preference. The compiler does not care where you place it. Placing it above the method is perfectly valid C#, and will not cause any issues.
The most standard conventions for C# code (including those enforced by tools such as StyleCop), would suggest that you place the field at the top of your class along with all other fields. The advantage of this is that you can easily glance at your class and see all locally stored data, as well as make sure you properly initialize, etc.
Be especially wary of having class fields that preserve state for a single method. Consider:
example.MouseMove eventThis will circumvent this problem of deciding where to put a heavily localized field.
For example:
class MouseTracker
{
private Point _prevMousePosition = new Point(0, 0);
//Maybe define some higher-level events here
public event ... MouseMoveWithHistory;
public void HandleMouseMove(object sender, MouseEventArgs e)
{
if (_prevMousePosition == Cursor.Position) return;
//Do stuff
//Trigger higher level events
}
}
Then, in your class:
private MouseTracker tracker = new MouseTracker();
...
//in your constructor
example.MouseMove += tracker.HandleMouseMove;
tracker.MouseMoveWithHistory += tracker_SomeLocalHandler;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With