I have come across a class which is non-static, but all the methods and variables are static. Eg:
public class Class1 {
private static string String1 = "one";
private static string String2 = "two";
public static void PrintStrings(string str1, string str2)
{
...
All the variables are static across all instances, so there is no point having separate instances of the class.
Is there any reason to create a class such as this?
Was the class written back in the .NET 1.x days? Static classes didn't appear until C# 2.0.
No. Make it a static class.
No. Some people dont realise that classes themselves can be static, and so don't include in the class definition. This is useful because it provides better intellisense options and ensures that future methods are added statically.
This also implicitly seals the class.
Static class provide :
Contains only static members.
Cannot be instantiated.
Is sealed.
Cannot contain Instance Constructors.
Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor.
No, if there are no instance members in the class then it should be static.
Related
I was wondering what are the general benefits (or drawbacks) of using a non-static class with a static method versus a static class with the same static method, other than the fact that I cannot use static methods from a non-static class as extension methods.
For example:
class NonStaticClass
{
public static string GetData()
{
return "This was invoked from a non-static class.";
}
}
Versus this:
static class StaticClass
{
public static string GetData()
{
return "This was invoked from a static class.";
}
}
What are the performance/memory implications of using one method over another?
NOTE: Suppose that I do not need to instantiate the class. My use-case scenario is limited to something like this:
Console.WriteLine(NonStaticClass.GetData());
Console.WriteLine(StaticClass.GetData());
The main benefit is that if you make the class static, the compiler will make sure that your class will only have static members.
So anyone reading the code, will instantly see the class can't be instantiated, and there is no interaction to be considered with any instances of the class. Because there can't be any.
At the clr level, there is no notion of static. A static class is both abstract and sealed, which effectively prevents inheritance and instantiation.
As for performance, I don't see any possiblities for compiler or runtime to optimize one over the other.
In this example, I would focus on expressing your intent as clear as possible to the readers. You can always optimize later.
There are some peculiarity/limitation:
you can't instantiate static class
you can't inherit static class
So if you suppose such a behavior for you class (e.g. helper/util or extension methods container), if you want to limit it's usage - make it static.
There are no benefits or drawbacks.
It's just architectual decision.
Use static only classes in cases of providing a function set or function libriary.
As you can not instantiate it, but you can use it like.
MyMathLibrary.Plot(...)
This types are usually imply state less behavior. I repeat, usually.
Use simple classes with static members when you have "normal" type but need somehow a stateless method, like for example:
public class MyType
{
.... //some members
public static MyType ReadFromXml(XmlReader reader) {}
public static void SaveToXml(MyType mt) {}
}
There is no a silver bullet, it's just a matter of architect choice.
Performance implications: basically none.
You can create an instance of NonStaticClass, but since it has no non-static overriden methods it's pretty much as useful as saying object obj = new object(), which is to say it's useful for maybe locking and that's about it. Making the class static prevent someone from new-ing it, but it's not like that does any real harm.
It's more of a self documenting way of saying there's no reason to create an instance of the class.
public class Class1
{
public static string Name="foo";
public void ChangeName(string _name)
{
Name=_name;
}
}
in some other class..
Class1 _c=new Class1();
_c.ChangeName("bar");
and the Name gets changed.. an instance changing a static member!
I thought a static member is available only for a Class. If a Class wants it can change its static members.
But here an instance is able to change it indirectly.Shouldn't an instance not be able to change it? When we create an instance it occupies its own space in the heap without having access to the static members of the Class. So what is really happening here?
The important part is
public static string Name="foo";
which creates a changeable static property. This allows for
Class1.Name="bar"
from outside the class as well as from inside the class - inside the class you can shorten this to
Name="bar"
which is exactly what is called via ChangeName("bar")
You might want to consider
public static readonly string Name="foo";
EDIT
If you want to be able to change the value only from within static methods, consider using a setter/getter construct with appropriate setter logic.
No, an instance is not kept from accessing static members. Instances are separate from each other, but static members are available both to static methods and instance methods.
As you have made it public, it's not even only methods in the class itself that can access it. You can change it from anywhere:
in some other class...
Class1.Name = "Albert";
MSDN clearly states :
"While an instance of a class contains a separate copy of all instance fields of the class, there is only one copy of each static field."
Hi all I just wanted to know whether a static class which inherits another class, can have access to the parent classe's non static members or not?
Please help. Thanks in advance.
A static class cannot inherit or implement any class or interface.
The point of inheriting or implementing a class or interface is to allow instances of your class to be used as the base type.
Since static classes cannot have instances, there's no point.
How should that work? A static class cannot be instantiated and therefor it will never have access to any non static members.
A static class is basically the same
as a non-static class, but there is
one difference: a static class cannot
be instantiated. In other words, you
cannot use the new keyword to create a
variable of the class type
You can view more information about static classes.
static class cannot inherited .
I think you can go with the same concept with SingleTon class and you can inherit the same.
A static class can't inherit from any classes or implement any interfaces.
A static class does implicitly inherit from Object, though. But since it's (also implicitly) abstract you can never have any instances of it, and so can never call any instance methods in Object. Also, it's (implicitly) sealed, and as such cannot have subclasses that would be instantiatable. As a corollary to these characteristics, it can't be used to type any variables, fields or parameters; and it can't be used as a type parameter (if these were possible, null would be the only valid value for such references).
Given all this, a static class does not look like a class at all, and I think would be better represented as a module.
I have a doubt that a static class can contain a private constructor.
Static classes cannot have instance constructors
http://msdn.microsoft.com/en-us/library/79b3xss3.aspx
The following list provides the main features of a static class:
Contains only static members.
Cannot be instantiated.
Is sealed.
Cannot contain Instance Constructors.
A static class cannot have any instance constructor ( see CS0710 ), whether it be public, private, protected or internal.
See the following article for more info.
Static Classes and Static Class Members (C# Programming Guide)
What would this constructor do? The class is static, so it is never instantiated. You can have a static constructor on a non-static class to initialize static fields, but on a static class, the only constructor that makes sense is the static constructor, and that gets called be the CLR.
Addition: Jon Skeet posted an article about the timing of the initialization of the static class (normally it's initialized on first use, but sometimes you want to initialize it when the program starts) and a possible change in .net 4.
Your doubt is correct.
A static class can only have a static constructor and public/private does not apply since your code can never call this constructor (the CLR does).
So you may not use a access modifier (public/private/...) on a static constructor.
rule is static classes cannot have instance constructors
Why can't a static class be inherited into a normal class?
If B inherits from (is a subclass of) A, that means an instance of B can be stored in a variable of type A, and its virtual methods will call those of class B.
For static classes, you don't have the concept of an instance of the class, so there's no way to inherit. You might have better luck with a static (singleton) reference to a regular class.
From Static Classes and Static Class Members (C# Programming Guide)
Creating a static class is therefore
basically the same as creating a class
that contains only static members and
a private constructor. A private
constructor prevents the class from
being instantiated. The advantage of
using a static class is that the
compiler can check to make sure that
no instance members are accidentally
added. The compiler will guarantee
that instances of this class cannot be
created.
Static classes are sealed and
therefore cannot be inherited. They
cannot inherit from any class except
Object. Static classes cannot contain
an instance constructor; however, they
can contain a static constructor.
As an alternative to inheriting from a static class, you can assign extension methods to interfaces.
You can not inherit a static class - The reason is simple. Static classes are marked as abstract and sealed in compiled IL which can be neither instantiated nor inherited.
This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.
There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.
(Mads Torgersen, C# Language PM)
Source:
Why can't I inherit static classes?