I have been learning C# for two weeks now, though it is not my first either second language. I have been wondering about the static word. I know I should have researched about this word long before...but this is the first time I realized how much confusing this word is for me. For what I have read:
A static class is a class which does not need to be instanciated to be used (
Class with single method -- best approach? ). This may have some advantages and some disadvanatges regarding testing, polymorphism etc.
But the static word can be applied also to classes, fields, methods, properties, operators, events and constructors !!! ( https://msdn.microsoft.com/en-us/library/98f28cdx%28v=vs.80%29.aspx ). Example:
Property:
private static string s = "";
Method:
public static void helperMethod() {
Console.WriteLine("Whatever");
}
Does the word static have a global meaning or employed in differents parts of the code the meaning can change?
class modifier
When static is applied to a class it indicates four attributes.
Contains only static members.
Cannot be instantiated.
Is sealed.
Cannot contain Instance Constructors.
property or function modifier (and events and methods)
When applied to properties and functions, e.g.
public Thing
{
static int SharedCount { get; set; }
static string GenerateName()
{
// ...
}
}
it means that the properties and functions will be accessible via the type name, without instantiating the class. This properties and functions will not be accessible via an instance of the class. So, both
var i = Thing.SharedCount;
var s = Thing.GenerateName();
Are valid and correct statements, Where as
var i = new Thing().SharedCount;
var s = this.GenerateName();
are both incorrect.
Code in functions and properties declared with the static modifier cannot access non-static members of the class.
member variables
Member variables declared with a static modifier, e.g.
class Thing
{
private static int sharedCount = 0;
private static readonly IDictionary<string, int> ThingLookup =
new Dictionary<string, int>
{
{ "a", 1 },
{ "b", 2 }
};
}
are shared by all static functions and properties and by all instances of the class.
static constructors
When applied to constructors, e.g.
class Thing
{
static Thing()
{
\\ Do this once and first.
}
}
static means the constructor will run once per AppDomain, when the type is first accessed. There are special edge cases around this.
operators
When an operator is overloaded for a type, this is always declared as static, e.g.
public static Thing operator +(Thing left, Thing right)
{
// Something special to do with things.
}
It is not logical for this to be declared at an instance level since operators must apply to types.
These distinctions are explained here, here, here and here.
Static members are items that are deemed to be so commonplace that there is no need to create an instance of the type when invoking the member. While any class can define static members, they are most commonly found within utility classes such as System.Console, System.Math, System.Environment, or System.GC, and so on.
Also the static keyword in C# is refering to something in the class, or the class itself, that is shared amongst all instances of the class. For example, a field that is marked as static can be accessed from all instances of that class through the class name.
Quick answer: No static remains the same contextually everywhere :
From dotnetperls:
These are called with the type name. No instance is required—this makes them slightly faster. Static methods can be public or private.
Info:
Static methods use the static keyword, usually as the first keyword or the second keyword after public.
Warning:
A static method cannot access non-static class level members. It has no this pointer.
Instance:
An instance method can access those members, but must be called through an instantiated object. This adds indirection.
C# program that uses instance and static methods
using System;
class Program
{
static void MethodA()
{
Console.WriteLine("Static method");
}
void MethodB()
{
Console.WriteLine("Instance method");
}
static char MethodC()
{
Console.WriteLine("Static method");
return 'C';
}
char MethodD()
{
Console.WriteLine("Instance method");
return 'D';
}
static void Main()
{
//
// Call the two static methods on the Program type.
//
Program.MethodA();
Console.WriteLine(Program.MethodC());
//
// Create a new Program instance and call the two instance methods.
//
Program programInstance = new Program();
programInstance.MethodB();
Console.WriteLine(programInstance.MethodD());
}
}
Output
Static method
Static method
C
Instance method
Instance method
D
In C#, data members, member functions, properties and events can be declared either as static or non-static.
Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.
Static members are often used to represent data or calculations that do not change in response to object state.
Static can be used in following ways:
Static data members
Static constructor
Static Properties
Static methods
More references :
MSDN
Static
Static in c#
What is static ?
The static keyword means generally the same everywhere. When it is a modifier to a class, the class's members must also be marked static. When it is a modifier to a member, (fields, properties, methods, events etc.) the member can be accessed using the following syntax:
ClassName.memberName
Note that operators must be declared static and extension methods must be in a static class which means it also has to be static.
Word static speaks for itself. If you have something that may change for every new object of some type - it's instance member and if it stays the same for all instances - it's static member.
From MSDN :
It is useful to think of static members as belonging to classes and
instance members as belonging to objects (instances of classes).
Source : static and instance members
Static members can be accessed via class object, something like MyClass.MyMember when instance members are only accessible on instance of a class (new MyClass()).MyMember
It's obvious that compiler takes some time to create instance and only then you can access its properties. So instance members works slower than static members.
In simple words , static property is not being changed across the classes , if your static member is affecting multiple classes once you change the value of it, it will be changed in every single class that is being affected by it.
Static method has to be static if you tend to use it in a static context (static class or so..)
Static class is the one which cannot be instantiated, e.g. static class Car{} this car will always have the same properties ( colour, size...)
There are many concepts related to Static keyword.
This answer will resolve your confusion about static.
Related
I'm a beginner in programming with C# and coming from a Python background.
I'm confused about the keywords public and static. Can someone please clarify the difference for me?
(Btw, I already know that Private variables/methods can never be accessed outside the function, whereas Public can be)
Here is just something I randomly tried to understand the difference between static, and non-static methods.
using System;
public class MainClass
{
public static void Main ()
{
int[] anArray = getAnArray();
foreach (int x in anArray)
{
Console.WriteLine (x);
}
MainClass m = new MainClass ();
foreach (int x in anArray)
{
m.Print(x);
}
}
public static int[] getAnArray()
{
int[] myArray = { 1, 2, 3, 4 };
return myArray;
}
public void Print(int x)
{
Console.WriteLine(x);
}
}
I understand that to use the non-static method Print, I first need to create an instance of the MainClass, then access the method by doing m.Print()
However I don't understand when exactly to use which. As far as I can see it would be a lot easier if Print was static, as I wouldn't need to create a new instance of my own function.
For eg, this would be simpler
private static void Print(int x)
{
Console.WriteLine (x);
}
And call the Print function with Print(x) instead of creating the instance of Main first.
So basically when to use what? When to use static or non-static in regard to not only methods but variables and even classes? (For eg when should I use public static class MainClass)
Small, self-explaining example of public/non-static and static methods in use:
Car car1 = new Car();
car1.setBrand("Ford"); //public non-static method
Car car2 = new Car();
car2.setBrand("Opel"); //public non-static method
Car.CompareParameters(car1, car2); //static method
Basically, non-static methods and properties describe objects of such class.
You can't call Car.setBrand() - non-static method using class name.
As a general rule of thumb:
Static methods
The static keyword makes the method directly accessible without having to create an instance of an object. As such, any state or side-effects it has will be static, ie "global". So only use static to create pure functions, ie methods that derive a return value from their inputs only, neither reading or writing state from outside the method.
The use of static is a trade-off between simplifying code and testing. The more side-effects you put in to a static method, the harder your code will be to test.
public methods
Anything marked public is accessible throughout your application. Marking something internal restricts it to just that assembly (you can view the term "assembly" as equivalent to a project in your solution") and private restricts it to only being assessable within a class/struct.
If you follow the principle of encapsulation, then the rule to follow is use private all the time, only using internal if you need to. And only use public if you really have to.
static members are class members, and shared between all instances of that class.
public methods/properties are available to other classes. It's possible to have a public static member which is available to other classes.
You can't access a non-static member from a static member.
If a function doesn't need access to any instance variables then it can be made static for a slight performance gain, but there are more useful ways to use static members.
Some uses for static off the top of my head:
Singletons (you create a protected constructor that is accessed by a static variable inside the class)
Console.WriteLine is static
Locks/semaphores (where there is only one available at the class level that is shared by all instances)
If something makes sense to be shared by all instances of a class, make it static
I came across the following code.
public class Test
{
public static Test Create()
{
return new Test
{
a1 =1,
b1="abc"
};
}
:
:
:
}
And in the calling class it is instantiated as below
static Test model = Test.Create();
What is the use of static keyword in the above line? What will be the difference if we don't use the static keyword? I'm using .NET 4 and VS 2010
EDIT
I know what is static in c#. The main reason I asked this question is why is it used when creating instance of class?
In this concrete presented code, don't see much sence of using this technique, but usually
you can do this in order to control your type instances creation.
For example: immagine that your class interacts with some COM object of the client, that can not be instantiated more the 10 times. To control that consumer of your API will not create more then 10 instances of your type, you can use this technique.
public class MyComWrapper {
private MyComWrapper () {} // MAKE CTOR PRIVATE SO NOONE CAN CREATE
// AN INSTANCE OF YOUR CLASS IF NOT WITH
// `static` METHOD CALL
static int counter = 0; //INSTANCE COUNTER
public static MyComWrapper Create()
{
if(counter >10) //MORE THEN 10, BAD !
throw new InvalidOperationException("Can not instantiate more then 10 instances");
counter ++;
return new Test
{
a1 =1,
b1="abc"
};
}
}
The static keyword makes it available without instantiating the object. The author is creating a function to instantiate the object in a specific way, but since it's the default constructor anyone can instantiate it.
Although not exclusively, along with making the constructor private, this is a pattern commonly used in the Singleton Pattern.
Static modifier belongs to the type itself rather than to a specific object.
You don't have to create an instance to use that static function. you can directly use the static function without creating an instance of the class.
If the static keyword is applied to a class, all the members of the class must be static.
It is simple. They are separate uses of static. The first one creates a static method in a non-static class. The second one create a static member of the "calling" class.
Your Test class itself is not static, so you are allowed to instantiate it.
To answer your question: if you do not use the static keyword in the calling class, it will be a "normal" instance member.
An example is worth a thousand stupid questions so:
public class OuterClass
{
public static class InnerClassEventArgs : EventArgs
{
public static int SomeInt;
}
}
and in a galaxy far far away:
public void SomeFunkyFunc()
{
OuterClass Instance1;
OuterClass Instance2;
Instance1.InnerClassEventArgs.SomeInt = 1;
Instance2.InnerClassEventArgs.SomeInt = 2;
//WHAT WOULD Instance1.InnerClassEventArgs.Someint == ?
}
Yes, I realize now that I've typed this that I've almost coded all I need to answer my own question. I'd rather not create a new project and go through the trouble if someone smarter than me knows off the top of their head.
Instance1.InnerClassEventArgs.SomeInt would equal 2. Static fields are shared across all instances of the class -- or as MSDN puts it:
The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.
Note that your specific example won't compile -- you'll get an error message that says "Cannot access static class 'InnerClassEventArgs' in a non-static context."
You'd have to use the following code instead, which hopefully makes the behavior more understandable:
OuterClass.InnerClassEventArgs.SomeInt = 1;
OuterClass.InnerClassEventArgs.SomeInt = 2;
A static class has exactly one instance, "shared" by all its usages (in your case, all instances of OuterClass). Therefore, the state of that object will be the sum of all changes made by any usage. In this simple example, SomeInt will be 2, regardless of which OuterClass instance you used to access it again (Instance1 or Instance2).
I'm conveniently ignoring all of the following:
A static class cannot inherit from any other class. InnerClassEventArgs thus cannot inherit from EventArgs.
Instance1 and Instance2 are not initialized; this will cause its own compile-time error if you use ReSharper ("X may not be initialized before accessing").
Static members (including nested static classes) cannot be accessed based on any one instance; you would access InnerClassEventArgs in static context.
I have two classes Class A and ClassB:
static class ClassA
{
static string SomeMethod()
{
return "I am a Static Method";
}
}
class ClassB
{
static string SomeMethod()
{
return "I am a Static Method";
}
}
I want to know what is the difference between ClassA.SomeMethod(); and ClassB.SomeMethod();
When they both can be accessed without creating an instance of the class, why do we need to create a static class instead of just using a non static class and declaring the methods as static?
The only difference is that static methods in a nonstatic class cannot be extension methods.
In other words, this is invalid:
class Test
{
static void getCount(this ICollection<int> collection)
{ return collection.Count; }
}
whereas this is valid:
static class Test
{
static void getCount(this ICollection<int> collection)
{ return collection.Count; }
}
A static class can only contain static members.
A static method ensures that, even if you were to create multiple classB objects, they would only utilize a single, shared SomeMethod function.
Technically, there's no difference, except that ClassA's SomeMethod must be static.
If you have a non-static class containing only static methods, you could create an instance of that class. But you can't use that instance meaningfully. NB: when you don't define a constructor, the compiler adds one for you.
A static class does not have a constructor, so you can't create an instance of it. Also the compiler gives an error when you add an instance method to it (where you meant a static method).
See also docs.
A static method belongs to the class and a non-static method belongs to an object of a class. That is, a non-static method can only be called on an object of a class that it belongs to. A static method can access only static members. A non-static method can access both static and non-static members because at the time when the static method is called, the class might not be instantiated (if it is called on the class itself). In the other case, a non-static method can only be called when the class has already been instantiated. A static method is shared by all instances of the class. Whenever a method is called in C++/Java/C#, an implicit argument (the ‘this’ reference) is passed along with/without the other parameters. In case of a static method call, the ‘this’ reference is not passed as static methods belong to a class and hence do not have the ‘this’ reference.
When should I prefer either a static or a normal class? Or: what is the difference between them?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace staticmethodlar
{
class Program
{
static void Main(string[] args)
{
SinifA.method1();
}
}
static class SinifA
{
public static void method1()
{
Console.WriteLine("Deneme1");
}
}
public static class SinifB
{
public static void method2()
{
Console.WriteLine("Deneme2");
}
}
public class sinifC
{
public void method3()
{
Console.WriteLine("Deneme3");
}
}
public class sinifD : sinifC
{
void method4()
{
Console.WriteLine("Deneme4");
}
sinifC sinifc = new sinifC(); // I need to use it :)
}
}
Static classes contain static objects that can't be instantiated multiple times. Usually what I use static classes for are to house static methods that provide calculations, general processing patterns, string output formats, etc. Static classes are light weight and don't need instantiation.
For instance System.IO.File is a static class with static a method Exists(). You don't create a File object to call it. You invoke it like this
System.IO.File.Exists(filePath)
Rather than doing this
System.IO.File myFile = new System.IO.File(filePath);
if(myFile.Exists())
{ /* do work */ }
If you require several objects in software, then you use dynamic classes. For instance if you have an inventory system you may have several Product objects and in that case you would use a dynamic class such as this
public class Product
{
public int ProductID { get; private set; }
public string ProductName { get; private set; }
public int Qty { get; set; }
public Product( int productID, string productName, int total )
{
this.ProductID = productID;
this.ProductName = productName;
this.Qty = total;
}
}
static classes cannot be instantiated or inherited.
static classes are marked as sealed and abstract by compiler in the output MSIL.
all members of static classes must be static as well.
only static classes can host extension methods.
static classes cannot be used as generic type arguments.
You can create instances of "normal" classes via the class constructor.
var normal = new Normal();
You cannot create instances of static classes. They can only have static methods.
Also worth noting is that you must declare extension methods in static classes.
From the MSDN documentation on static classes:
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
In simple terms:
A static class cannot be instantiated using the new keyword.
All methods in a static class must be static and can be called directly without instantiation.
A "normal" class MUST be instantiated however any static methods in a "normal" class can be called without instantiation.
Non static methods in a "normal" class cannot be called without first instantiating the containing class.
Static members can be called without using an instance of the class. For example, a static Math class with an Area method call be called by Math.Area without instantiating the Math class first.
A normal class is one which you can instantiate and can use with objects.
A static class is one which can not be instansiated and can't be extended.
That means a static class is sealed and abstract by default, you may look at the
MSIL of a static class compiler puts sealed and abstract in front of a static class.
So, because a static class can't be instantiated, you can't have instance methods defined
on static classes, so all methods must be static and public ofcourse as you would want to
use them.
A static class is singleton by default.
Static classes are used for defining extension methods because you don't want to
instansiate them.
Static classes are like global provider of unique services.
I hope that make sense to you and will help you to understand the static classes.
It might help to think of "static" and "instance" in terms of memory addressing.
An object that is static exists in one and only one location in memory; you can't create instances of it because by definition it has been stated that it will be found in one particular location. It is "static" and unchanging. The creation of the object is implicit rather than explicit.
var result = Math.Pow(3, 3); // static - Math class can't be instanced
An object that isn't static can be instanced one or more times; you're saying, "Create for me an object of this type" and the object is given a memory address. You can create multiple instances that all exist in different memory addresses. The creation of the object is explicit using the new keyword.
var Ted = new Employee(); // instance - creates a new object at a new address
This is where people get into trouble in ASP .NET web programming; static classes are created once per Application Domain and their constructors are therefore only called once.
A static class is one that cannot be instantiated. Therefore, it cannot be used as a 'template" for multiple instances of some object that conforms to the class definition as a normal class can. In a normal class, the data members defined are created for each "instance" of the class, and each "instance" has it's own set of these data members, so these instances represent individual "entities" or complex in-memory data structures for some object (which you coded the class to represent).
When you define (code) a static class, all of it's data fields must also be static, meaning that they cannot be instantiated once for each instance of the class, (you can't create instances of a static class ). Static classes are useful only when you just need a container to hold methods that do not depend on the state of some object or data structure being managed by the application (like an add function, or a string formatter, etc.)