static class

  • Thread starter Thread starter someone
  • Start date Start date
S

someone

Is it possible to declare a class as static? I can't seem to do that.

What if I need a class that I don't want instantiated? It will contain only
static members.

Thanks.
 
Do you know how the Math class is defined?

If I try:
Math m = new Math();
I get:
'System.Math.Math()' is inaccessible due to its protection level

But of course I can do this:
double d = Math.PI;

That's the type of functionality I want.

Thanks.
 
I'm pretty new to C# so please someone correct me if I'm wrong but, if I
understand correctly, you can use double d = Math.PI; because Math makes
available a public static property, method, field, etc titled PI (or
whatever). Create your class as normal and create your
methods/properties/fields as static.
 
Do you know how the Math class is defined?
If I try:
Math m = new Math();
I get:
'System.Math.Math()' is inaccessible due to its protection level
Make constructor private (if you don't want to instantiate objects of your
class, you don't realy nead constructor, but if you do so, you will get
warning if you try Myclass m = new Myclass())
But of course I can do this:
double d = Math.PI;
Make all members static
That's the type of functionality I want.
You will get what you want ;)))
Greetings
 
Someone,
Make the default constructor of your class private, so no one can create an
instance of the class.

Make the class itself sealed, so no one can derive from it.

Only create static members in the class.

Hope this helps
Jay
 
Hi,

You CANNOT make a class static, you can make methods, properties and
variables of that class static , though.

If you don't want an instance of that classes to be created you can declare
the constructor as private therefore nobody can create it. Also remember
that if you are going to have only static method then this constructor will
never be called, therefore you will need to have a constructor marked as
static

Hope this help,
 
Ignacio Machin said:
You CANNOT make a class static, you can make methods, properties and
variables of that class static , though.
Agreed...

If you don't want an instance of that classes to be created you can declare
the constructor as private therefore nobody can create it.
Agreed.

Also remember
that if you are going to have only static method then this constructor will
never be called, therefore you will need to have a constructor marked as
static

Not agreed. You *may* need a static constructor, but in many cases you
don't.
 
Hi Jon,

Not agreed. You *may* need a static constructor, but in many cases you
don't.

Ok, you are right, the correct word is "may" and no "need" , the english is
not my first language and sometimes I mix the words :)


Cheers,
 
Back
Top