I occasionally find myself in a situation where I have a variable that will only ever be used by one method in a class. Currently I use an instance variable, but it seems like bad design to have this variable visible to the rest of the class. Example just to illustrate a situation where I want this:
private Window _Window;
private void Show()
{
if (_Window == null)
{
_Window = new Window();
_Window.Closed += delegate { _Window = null; };
_Window.Show();
}
_Window.BringIntoView();
}
The instance variable only exists to prevent more than one window being created at a time, so there’s no reason for the rest of the class to know about it. I’m reminded of C++’s ability to define static variables within a function.
Is there any way to achieve something like this is C#? Or am I stuck with the decision of choosing between bad design and bad encapsulation? (Assuming that this method truly doesn’t warrant a class of its own.)
No.
Well, I’m not sure you’re actually stuck with either of those. It sounds like this is part of the state of the object, even if none of the other methods need to refer to that aspect of its state. Would it be logically wrong for other code within the same class to refer to this aspect of state? If so, why?
(Admittedly I’ve occasionally wished for the ability to declare a field “within” a property declaration, forcing the rest of the class to access the state via the property…)