Sunday, 15 January 2012

c# - Private Static Members inside a Static Class... Good idea? -



c# - Private Static Members inside a Static Class... Good idea? -

i created static class private static fellow member within of it. private static fellow member accessible of static class methods.

this happened while wasn't paying attention, realized had done, , - interestingly plenty - seems working fine in application. nonetheless, seemed silly thing (coming c++), have been searching around trying find more info on whether supposed possible and/or if considered or bad practice, haven't been able find @ creating private static members within static class in c#.

it seems static methods within static class have implicit "this" variable (since i'm able phone call other methods without qualifying them class name), feels peculiar me.

i hoping of might have thoughts whether thought or not, , why c# makes possible @ all.

the class:

public static class controlhighlighter { private static panel highlightpanel = null; public static void highlight(control command = null, int thickness = 1) { removehighlight(); if (control != null) { if (control.parent != null) { highlightpanel = new panel(); control.parent.controls.add(highlightpanel); highlightpanel.location = new point(control.location.x - thickness, control.location.y - thickness); highlightpanel.size = new size(control.size.width + (2 * thickness), control.size.height + (2 * thickness)); highlightpanel.sendtoback(); highlightpanel.backcolor = systemcolors.highlight; } } } public static void removehighlight() { if (highlightpanel != null) { highlightpanel.dispose(); highlightpanel = null; } } }

in general, there's nil wrong having private static members in static classes (or in non-static classes). pose potential problems, though: when application multithreaded, these static members shared across threads have apply locking around them.

since never know if need create application multithreaded, it's best maintain number of static variables minimum - static variables shared between threads must protected through locks or other synchronization primitives. it's far easier kind of work ahead of time patching problems later on.

however, in specific example, you're putting ui command in static variable - i'd advise against. ui controls live on ui thread , must invoked when called different thread. threading issues aside, putting command in static variable recipe problem - static variable requires careful bookeeping clean - if form hosting command goes away, static reference still maintain in memory (because command cannot go away). can lead kinds of hard-to-find problems.

if you're not familiar static in c#, recommend reading msdn more detail.

c# static

No comments:

Post a Comment