Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / March 2008

Tip: Looking for answers? Try searching our database.

Static Classes

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Prefers Golfing - 21 Mar 2008 23:56 GMT
We are wrapping web ui controls in our own classes. Is there a downside
(performance/memory management) to making a class static?
Peter Morris - 22 Mar 2008 10:37 GMT
> We are wrapping web ui controls in our own classes. Is there a downside
> (performance/memory management) to making a class static?

No.  But you must take into account that page requests are multi-threaded,
and without the safety net of having instance members you will need to
ensure all of your code is thread safe.

Pete
Bob Powell [MVP] - 22 Mar 2008 10:44 GMT
All classes should be static. So should all methods. We should
systematically expose fields as public and do away with object oriented
programming too.

Before taking up C#, did you write Visual Basic by any chance?

But seriously..

A static or utility class will have no instance data. Each method must be
self contained. This is to say that the method will perform some instant
task, with or without parameters and possibly return some result without
maintaining any state.

A classic utility class is System.Math.

Signature

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

> We are wrapping web ui controls in our own classes. Is there a downside
> (performance/memory management) to making a class static?
Jon Skeet [C# MVP] - 22 Mar 2008 11:16 GMT
> All classes should be static. So should all methods. We should
> systematically expose fields as public and do away with object oriented
[quoted text clipped - 10 lines]
>
> A classic utility class is System.Math.

Well, not quite. It's perfectly possible to have a static class with
state. StaticRandom in MiscUtil is such a class. It's just that all the
state is shared, because you can only have static fields within a
static class.

But yes, typically most uses of static classes don't have any state at
all.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

Bob Powell [MVP] - 23 Mar 2008 12:49 GMT
I know that it's possible but it's also possible to drive the wrong way on
the freeway. Its not necessarily a good idea ;-) although I admit that I
have even done that recently when I turned around to assist someone who had
been in a terrible accident. I guess there are exceptions to every rule.

I was unaware of your little library. I will peruse it with interest.

Signature

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

>> All classes should be static. So should all methods. We should
>> systematically expose fields as public and do away with object oriented
[quoted text clipped - 18 lines]
> But yes, typically most uses of static classes don't have any state at
> all.
Bill Woodruff - 23 Mar 2008 13:34 GMT
All classes should be static. So should all methods. We should
systematically expose fields as public and do away with object oriented
programming too.

Before taking up C#, did you write Visual Basic by any chance?

But seriously..

A static or utility class will have no instance data. Each method must be
self contained. This is to say that the method will perform some instant
task, with or without parameters and possibly return some result without
maintaining any state.

A classic utility class is System.Math.

Signature

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

> We are wrapping web ui controls in our own classes. Is there a downside
> (performance/memory management) to making a class static?
Bill Woodruff - 23 Mar 2008 13:52 GMT
Bob Powell [MVP] wrote :

"A static or utility class will have no instance data. Each method must be
self contained. This is to say that the method will perform some instant
task, with or without parameters and possibly return some result without
maintaining any state.

A classic utility class is System.Math."

i have been using static classes in certain circumstances (in WinForms apps)

1. function repository model : there is a thematically related set of
functions which several independent classes (or winforms) may need to call.
this usage i consider very consistent with the way .NET itself packages
certain function libraries as static.

2. global state container model :  there are pointers to objects (like
winforms), or constant values, which several different independent classes
or winforms need access to. this usage i waver on in the sense that i feel
in many circumstances techniques like injection of a form or object
reference, or writing formal Properties with tight control over set/get is
better.

The hueristic in my head goes something like : "if there's one and one only
... consider 'static' " I'm still baffled by my inability to use an array of
structs in a static class as I expected; and that's one (among many) reasons
why I am going to buy Skeet's book tomorrow :)  But while structs have
"bitten" me, my experience using static classes has been sweet.

I've found that the "extra discipline" required to write static classes is
beneficial to me, though I can't justify that statement with computer
science theory. And I have not considered the issues of using static classes
with multi-threaded apps.

I put these thoughts out with the goal of learning from folks like you, and
J Skeet, and H. Wagner, P. Duniho, and N. Paladino, and everyone else, how
"out of whack" my thinking is :)

best, Bill Woodruff
Bob Powell [MVP] - 23 Mar 2008 14:12 GMT
Hi Bill, Inline...

> Bob Powell [MVP] wrote :
>
[quoted text clipped - 13 lines]
> this usage i consider very consistent with the way .NET itself packages
> certain function libraries as static.

This is the classic example such as System.Math. I have no problem with
this.

> 2. global state container model :  there are pointers to objects (like
> winforms), or constant values, which several different independent classes
> or winforms need access to. this usage i waver on in the sense that i feel
> in many circumstances techniques like injection of a form or object
> reference, or writing formal Properties with tight control over set/get is
> better.

I try to enforce that people who work on teams that I advise stay away from
this model.
The problem here is that as soon as we start using static as a convienience
in this way, the temptation is to continue in the same vein and then we end
up with a massive globally centric pile of spaghetti. You may find it ok for
projects that you do yourself or with a small team but try enforcing good
practice when there are 450 developers working in five different
technologies and they all need the most convienient method because the boss
says they need to be "reactive"

> The hueristic in my head goes something like : "if there's one and one
> only
[quoted text clipped - 17 lines]
>
> best, Bill Woodruff
Jon Skeet [C# MVP] - 23 Mar 2008 15:24 GMT
> The hueristic in my head goes something like : "if there's one and one only
> ... consider 'static'

Consider it - but also consider that even if there's only one
*production* implementation it may be useful to encapsulate the
behaviour in an interface and mock it for *test* purposes. I often end
up with interfaces like that - it may look pointless when there's only
one class in source control which implements each interface, but
introduce Rhino.Mocks into the picture and things change very quickly
:)

> I'm still baffled by my inability to use an array of
> structs in a static class as I expected; and that's one (among many) reasons
> why I am going to buy Skeet's book tomorrow :)  But while structs have
> "bitten" me, my experience using static classes has been sweet.

Hmm... could you explain what problem you're having with an array of
structs? I wouldn't like to guarantee that my book will answer that
issue, but if you promise to buy the book anyway, I'll cast my eye over
it :)

> I've found that the "extra discipline" required to write static classes is
> beneficial to me, though I can't justify that statement with computer
> science theory. And I have not considered the issues of using static classes
> with multi-threaded apps.

No more threading issues than normal, really - any shared writable
state needs to be protected as usual, but that's all I can really think
of.

> I put these thoughts out with the goal of learning from folks like you, and
> J Skeet, and H. Wagner, P. Duniho, and N. Paladino, and everyone else, how
> "out of whack" my thinking is :)

LOL. I'd certainly agree that static classes are useful - but bear in
mind the testing bit earlier.

One static class I haven't put in MiscUtil yet but which I may do at
some point is one to provide the equivalent of DateTime.Now/UtcNow etc,
but in a way which helps with testing. It's useful to have "real" time
normally, but occasionally be able to control time for tests. For
instance, if you've got a cache which is meant to throw stuff out after
an hour, it's really handy to be able to "fake" an hour passing :)

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

Ben Voigt [C++ MVP] - 24 Mar 2008 15:09 GMT
>> The hueristic in my head goes something like : "if there's one and
>> one only ... consider 'static'
[quoted text clipped - 6 lines]
> introduce Rhino.Mocks into the picture and things change very quickly
> :)

Which is why singleton pattern is a reasonably good way of dealing with
this.  One instance of the class, created and stored in a static variable
(in the same class or another).  Then you get global visibility and the
ability to redirect to a mock by changing only one field.

>> I'm still baffled by my inability to use an array of
>> structs in a static class as I expected; and that's one (among many)
[quoted text clipped - 30 lines]
> stuff out after an hour, it's really handy to be able to "fake" an
> hour passing :)
Bill Woodruff - 25 Mar 2008 03:46 GMT
Ben Voigt MVP wrote : in response to Jon Skeet MVP comments on static
classes :

"Which is why singleton pattern is a reasonably good way of dealing with
this.  One instance of the class, created and stored in a static variable
(in the same class or another).  Then you get global visibility and the
ability to redirect to a mock by changing only one field."

I am not familiar with using Rhino or "mock."

But I would like to ask you why a static class, particularly one without a
constructor, is NOT inherently an "incarnation" of the Singleton pattern.
If your reply knocks me over with common sense, I won't complain :)

thanks, Bill Woodruff
Peter Duniho - 25 Mar 2008 04:22 GMT
> [...]
> I am not familiar with using Rhino or "mock."
>
> But I would like to ask you why a static class, particularly one without  
> a
> constructor, is NOT inherently an "incarnation" of the Singleton pattern.

I don't know what "Rhino" or "mock" refers to either.  However, as far as  
your question goes, it seems to me that one obvious difference between a  
static class and the singleton pattern is that a singleton, being an  
instanced object, can implement interfaces and inherit other classes.

The two share a lot in common, I'll grant.  But I don't think that a  
static class is inherently a singleton itself.

Pete
Bill Woodruff - 25 Mar 2008 05:16 GMT
Peter Duniho wrote : "... However, as far as your question goes, it seems to
me that one obvious difference between a  static class and the singleton
pattern is that a singleton, being an instanced object, can implement
interfaces and inherit other classes.

The two share a lot in common, I'll grant.  But I don't think that a  static
class is inherently a singleton itself."

Some good points there to think on, Peter. Appreciated. One thought that
occurs to me is to wonder (I guess I'll have to go back to the "epiphany" as
revealed by the Gang of Four to check on it) if the "original" concept of a
Singleton had any reference to Interfaces or Inheritance. But that could
just turn out to be a pedantic quest. Me like Interfaces, Rhino or no Rhino.

The thought also comes that most of us writing WinForms applications make
use of a Static class, Program.cs, every time we use the default WinForms
app template to start a new project :) Of course that's not a Singleton
since you can run multiple copies of the .exe. I've seen a variety of ways
to make sure one-and-only-one instance of your app runs.

So maybe I should be careful to distinguish between Singleton as a pattern
that enforces one-and-one-only of some object, and "Singleton" as a method
of having a single-instance-at-a-time-running in the context of WinForms
apps ?

Interfaces, as contracts that enforce, appeal to me but I keep sometimes
wondering why there isn't an Interface "flavour" that specifies the scoping
of what it requires you code : i.e., that says, in effect : "when you
inherit from this Interface, you must implement this as static, this as
public, and this as private readonly."  From an "enforcement" point of view
I like that, but realize it's really not what Interfaces as we have them now
are.

best, Bill
Peter Duniho - 25 Mar 2008 07:46 GMT
> Some good points there to think on, Peter. Appreciated. One thought that
> occurs to me is to wonder (I guess I'll have to go back to the  
[quoted text clipped - 4 lines]
> just turn out to be a pedantic quest. Me like Interfaces, Rhino or no  
> Rhino.

I can't speak for what the GoF book says (haven't read it...I have to  
admit, though it's not specifically why I haven't read the book, I'm a bit  
put off by the whole "Gang of Four" moniker...what's up with that?), but  
Wikipedia's entry seems to me to not only call out a singleton as  
specifically an instanced object, but it even discusses the difference  
between a singleton and a static class.
http://en.wikipedia.org/wiki/Singleton_pattern

> The thought also comes that most of us writing WinForms applications make
> use of a Static class, Program.cs, every time we use the default WinForms
> app template to start a new project :)

Sort of.  I mean, the Program class is static by default, but there's no  
real requirement that it be so.  If you thought there was some value in  
making it an instantiable class, you could, singleton or otherwise.  In  
fact, the console application template doesn't make it static.

> Of course that's not a Singleton
> since you can run multiple copies of the .exe. I've seen a variety of  
> ways
> to make sure one-and-only-one instance of your app runs.

I think the two are not really the same thing.  But at the same time, I'm  
perfectly comfortable saying that you could have a singleton Program  
class, or a singleton application, or both, or neither.

I'd admit the term doesn't seem directly applicable according to the  
Wikipedia description of a singleton (it seems to imply that a singleton  
_must_ be a class in an object oriented language).  But it seems to me  
that one value of the idea of design patterns is that they are general  
enough to be applicable in a variety of settings, as long as the objects  
being described behave in a certain way and can be controlled in a certain  
way.

A Windows process isn't normally managed the way a singleton is (i.e. with  
some global entity that manages instantiation and caching of an instance),  
but it _could_ be, and even in the more common case of a process checking  
for itself already existing, I think it's a reasonable expansion of the  
idea to call it a singleton application in that case.

> So maybe I should be careful to distinguish between Singleton as a  
> pattern
> that enforces one-and-one-only of some object, and "Singleton" as a  
> method
> of having a single-instance-at-a-time-running in the context of WinForms
> apps ?

Depends on who you're talking to.  I don't think you need to be.  :)

> Interfaces, as contracts that enforce, appeal to me but I keep sometimes
> wondering why there isn't an Interface "flavour" that specifies the  
[quoted text clipped - 6 lines]
> now
> are.

Right, it's not.  Interfaces describe the public API that a class instance  
exposes.  It's a way of passing an object around without caring what the  
object really is, but rather just caring about what it can do.

In that context:

    -- static interfaces don't make sense because you can't pass around a  
static class
    -- private interface members don't make sense because that defines an  
implementation detail, not a public API

I don't think a contract requiring a private member would ever make  
sense.  After all, no one would ever see the private member except the  
class implementing it.  A protected member makes more sense, but that's  
actually possible via abstract classes.  You can only inherit one abstract  
class in C#, but then you'd only ever be able to see one implementation of  
a protected member in C# either (for the same reason).

In other words, while I think I understand where the original thought  
you've expressed comes from, I also think that the system would become  
inconsistent if interfaces supported those kinds of things.

Pete
Ben Voigt [C++ MVP] - 25 Mar 2008 14:36 GMT
> So maybe I should be careful to distinguish between Singleton as a
> pattern that enforces one-and-one-only of some object, and
> "Singleton" as a method of having a single-instance-at-a-time-running
> in the context of WinForms apps ?

The word singleton by itself usually refers to "unique within the address
space", if you mean unique within a larger system (entire system, LAN, WAN,
etc) you'd have to qualify it.

> Interfaces, as contracts that enforce, appeal to me but I keep
> sometimes wondering why there isn't an Interface "flavour" that
[quoted text clipped - 3 lines]
> an "enforcement" point of view I like that, but realize it's really
> not what Interfaces as we have them now are.

static classes are inherently sealed, while singletons need not be.  Take
MFC's WinApp class for example.  Only one can exist, but it is rarely an
instance of WinApp itself, usually it is a derived class.

> best, Bill

Rate this thread:







Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.