Net-informations.com
SiteMap  | About    

What does the keyword static mean

Static keyword

Static Classes and class members are used to create data and methods that can be accessed without creating an instance of the Class. The keyword Static can be applied to the Classes, field, method, properties, operator, event and constructors.

static

We can call variables and methods of static classes without creating an instance of the class. That means you cannot use the new keyword to create a variable of the class type. We can call static members and methods directly from classes like the following :

Product.price = 100; Product.showInfo();

When we declared a variable or method as static, what really happens is that all the instances of the class share the same static variable. That means, where ever we used this class, the class will share the same copy of that variable and methods.

When we try to create an instance of the above class it will generate a compile time error.

Product p = new Product(); //wrong p.price = 100;

The above code generate a compilation error.

When we use static keyword in .Net ?

We can use them when we need to maintain information applicable to the entire class. Static class can contain only static members, that is static methods, static fields, static properties. This is because static class cannot refer to any instance members. Static member belongs to that particular class and not to any object of the class. It is important to note that a static method cannot access non-static fields.

What are static Classes?

Static Classes use the static keyword before a class name and whose objects can't be created. Also it should only have static member variables and methods. They can't be inherited and these classes are sealed by default. Normally it is used to group related static methods in class.

The advantage of static keyword is that it will make your code a bit faster since no object creation is involved.









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.