In common run throughs, static means fixed or not changing unless someone changes it. Similarly, in computer programming languages, a static variable is a variable that has been allocated "statically", meaning that value assigned to a static variable remains same throughout the entire run of the program.
Let us understand the concept of static in a simpler way using the below use case: Your brother or sister is studying in class V and there can be a maximum of 30 total students enrolled in his/her classroom.
Consider if one student consumes more food and puts on weight. Will it affect the value of the weight of all the students? The answer is No. Each one of them has different values for weight.
So, the weight of the student is a non- static variable. Each student has its own value for that.
Let's say, at the beginning of the session, 30 students sign up in your sister or brother’s class. I ask you one question; how many students can be enrolled in the classroom? You will tell me 30. I ask the same question to another student. All will say 30.
After a few months one classmate doesn't like your school and s/he discontinues ... Drops out:)..!!! . I ask the same question; how many students can be enrolled in classroom? You will tell me 30. I ask the same question to another student. All will say 30.
So the maximum number of students that can be enrolled in the class is a static variable that will remain the same throughout the entire run of the program until unless the school administration makes any change to the value.
Static in C#C# programs includes "static" keywords just like other programming languages such as C++, Java, etc. The Static keyword can be applied on classes, variables, methods, properties, operators, events and constructors. However, it cannot be used with indexers, destructors or types other than classes.
Prefixing the static modifier before classes, variables, methods, properties, operators, events and constructors makes them static, meaning the value assigned to it will remain the same throughout the entire run of the program and can be accessed from anywhere in the program without any object reference provided it has been declared as public.
Static Member VariablesThe static member is callable on a class even when no instance of the class has been created. 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.
ScopeIn terms of scope and extent, static member variables have the entire run of the program, but may have more limited scope.
Local VariableDeclaring a private static variable in a class makes it non-accessible from another class but it can be accessed from within the class; for example to store the count of instances we can declare a private static variable and public instance property return count of instances.
- publicclassStaticVariableClass {
- ///<summary>
- /// Default Constructor which increment static variable _numberOfInstances
- /// which is meant is to store the count of instances of this class
- ///</summary>
- public StaticVariableClass() {
- _numberOfInstances = ++_numberOfInstances;
- }
- ///<summary>
- /// Local Static variable - will not be accessible from
- /// another class or any method outside this class.
- /// this variable is to store the count of instances of this class
- ///</summary>
- privatestaticint _numberOfInstances = 0;
- ///<summary>
- /// Public instance method which returns the value assigned to the
- /// local static variable _numberOfInstances
- ///</summary>
- publicint NumberOfInstances {
- get {
- return _numberOfInstances;
- }
- }
- }
- Static variable will not be accessible using StaticVariableClass._numberOfInstances directly but will be accessible after creating an object of the class StaticVariableClass.
- classProgram {
- staticvoid Main(string[] args) {
- StaticVariableClass staticVariableClassObject = newStaticVariableClass();
- Console.WriteLine(staticVariableClassObject.NumberOfInstances);
- Console.ReadLine();
- }
- }
As we can see the default constructor increments the value of static variable _numberOfInstances whenever class is instantiated using the new keyword. Output of this program will return 1.
Global VariablePlease note that C# is an object-oriented programming (OOP) language and does not support global variables directly. The solution is to add a static class and declare a public static variable or declare a public static variable in a class makes it accessible from anywhere in the program meaning a global variable. Using a global variable violates the OOP concept a bit, but can be very useful in certain circumstances, for example to store the maximum number of students that can be enrolled in class we can declare a static global variable.
- publicstaticclassStaticGlobalVariable {
- ///<summary>
- /// Global Static variable – will be accessible from another
- /// class or any method outside this class
- /// This variable is to store the count of maximum number of students
- /// that can be enrolled in the class
- ///</summary>
- privatestaticint _maximumNumberOfStudents = 30;
- ///<summary>
- /// Public instance method which returns the value assigned to
- /// the local static variable _maximumNumberOfStudents
- ///</summary>
- publicstaticint MaximumNumberOfStudents {
- get {
- return _maximumNumberOfStudents;
- }
- }
- }
- classProgram {
- staticvoid Main(string[] args) {
- Console.WriteLine("maximum students that can be enrolled in a class - {0}", StaticGlobalVariable.MaximumNumberOfStudents);
- Console.ReadLine();
- }
- }
Non Static methods and properties can access both static and instance (non-static) fields and events.
- ///<summary>
- /// This is the class that defines and demonstrate Non Static method
- /// access Static field
- ///</summary>
- publicclassNonStaticMethodAccessStaticMember {
- ///<summary>
- /// Local Static variable - will not be accessible from
- /// another class or any method outside this class
- /// This variable is to store the count of instances of this class
- ///</summary>
- privatestaticint _numberOfInstances = 0;
- ///<summary>
- /// This is the instance method (non-static method) that
- /// access local static variable.
- /// This method compile successfully
- ///</summary>
- publicvoid PrintNumberOfInstances() {
- Console.WriteLine("Number of Instances: {0}", _numberOfInstances);
- }
- }
- ///<summary>
- /// This is the class which act as an instance class meaning
- /// instance of class can be created
- ///</summary>
- publicclassStaticMethodAccessNonStaticMember {
- ///<summary>
- /// Local instance variable - will not be accessible from another
- /// class or any method outside this class
- /// This variable is to store the count of instances of this class
- ///</summary>
- privateint _numberOfInstances = 0;
- ///<summary>
- /// This is the instance method which access local static variable.
- /// This method compile successfully
- ///</summary>
- publicstaticvoid StaticPrintNumberOfInstances() {
- Console.WriteLine("Number of Instances: {0}", _numberOfInstances);
- }
- }
On Compilation the above code gives the below error:
- Static methods and properties cannot access an instance variable of any object
- Static methods and properties can access instance variable of any object if passed in a method parameter explicitly.
- publicclassRegistration {
- privateStudent _selectedStudent = null;
- privateCourse _selectedCourse = null;
- ///<summary>
- /// Dummy Students data
- ///</summary>
- privatereadonlyList < Student > _students = newList < Student > () {
- newStudent() {
- StudentId = 1, FirstName = "Hemant", LastName = "Jindal"
- },
- newStudent() {
- StudentId = 2, FirstName = "Titiksha", LastName = "Jindal"
- }
- };
- ///<summary>
- /// Dummy Courses data
- ///</summary>
- privatereadonlyList < Course > _courses = newList < Course > () {
- newCourse() {
- CourseId = 1, CourseName = "Computer Programming"
- },
- newCourse() {
- CourseId = 2, CourseName = "Artifical Intelligence"
- },
- };
- ///<summary>
- /// This method access static method defined in another class and
- /// pass instance variable of an object
- ///</summary>
- ///<param name="studentId"></param>
- ///<param name="courseId"></param>
- publicvoid Register(int studentId, int courseId) {
- //basis on student identifier retrieve a student from students
- _selectedStudent = _students.FirstOrDefault(x => x.StudentId == studentId);
- //basis on course identifier retrieve a course from available courses
- _selectedCourse = _courses.FirstOrDefault((c => c.CourseId == courseId));
- StudentCourseEnrollment.Enroll(_selectedStudent, _selectedCourse);
- }
- }
- ///<summary>
- /// This is the class that defines and demonstrate Static method
- /// access instance variable of any object if passed in a
- /// method parameter explicitly
- ///</summary>
- publicclassStudentCourseEnrollment {
- publicstaticvoid Enroll(Student student, Course course) {
- Console.WriteLine("{0} is enrolled to the course {1}", student.FirstName, course.CourseName);
- }
- }

Viknaraj ManogararajahPosted Jul 21, 2018, 10:53 PM
Nice Article, Thank you for sharing
suman royPosted May 30, 2018, 7:27 AM
Great article for learning static concepts in c# with code.