Constructors in a Static Class

J

Jordan S.

Just learning OOP here... Does it make sense to have a constructor in a
static class? Say I have a class with a constructor and then mark that class
as static; will it (the default constructor) get called when the application
starts? or are any/all constructors ignored in static classes?

Thanks.
 
S

Sericinus hunter

Jordan said:
Just learning OOP here... Does it make sense to have a constructor in a
static class? Say I have a class with a constructor and then mark that class
as static; will it (the default constructor) get called when the application
starts? or are any/all constructors ignored in static classes?

It will not compile, unless the constructor is also marked static.
And yes, it may make sense, when you need lazy initialization.
 
M

Marc Gravell

static constructors are automatically executed (generally) when the static
class is first used by the runtime, which could be a while into your app.
But yes, they are definitely useful. For generic static classes the ctor is
executed once per template permutation.

Marc
 
G

Guest

Jordan S. said:
Just learning OOP here... Does it make sense to have a constructor in a
static class? Say I have a class with a constructor and then mark that class
as static; will it (the default constructor) get called when the application
starts? or are any/all constructors ignored in static classes?

Static constructor make sense if you have static variables that you need to
initialize. Static constructors are invoked the first time the class is
accessed.
Be sure to mark the constructor as static.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top