French Boy
French Boy

Reputation: 1501

Is using a static property in a form bad practice knowing that there's only one instance of the form?

In a complex form, I have a property called Readonly that determines if everything is editable or not. So far, I'm passing this property to every sub custom control in this form by constructor, and in other places, I access the form itself to get the value.

But this is quickly becoming too complex.
I'm thinking of making this property Static in the form knowing that there's only one instance of this form in the application.

Is it OK to use this property as a static in this case? Or it's a bad practice even there's only one instance of the form.

Upvotes: 5

Views: 389

Answers (3)

jgauffin
jgauffin

Reputation: 101166

Here is an alternative solution:

  1. Add the controls to your form as usual
  2. Create an interface called IReadOnlyToggable which has a IsReadOnly property and let the form implement it.
  3. Add the following property to your custom controls:

code:

public bool IsFormReadOnly
{
    get 
    {
        var form  = ParentForm as IReadOnlyToggable;
        return form != null && form.IsReadOnly;
    }
}

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1063599

Simply ask yourself: does this relate to the form or to the type of form. Hypothetically, if there were more than one form - would they all be readonly/not at the same time? Or would it be per form?

Then: you have the answer. I suspect it should be instance (non-static).

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1039228

Even if your have a single instance of the form using a static field doesn't make it safe. You could have multiple threads that cause problems. Not to mention the difficulty to unit test your application. Personally I try to avoid static fields as much as possible.

Upvotes: 4

Related Questions