Skip to main content

The Static keyword in C# with Example

The Static keyword in C# with Example

Static is a keyword or a modifier which is use to make a classmethods or variable properties as not instantiable, that means we cannot instantiate the items which we declared with a static modifier.

 

The static members which we declared can be accessed directly with a type name. Suppose if we apply a static modifier to a class property or to a method or variable, then we can access those static members directly with a class name, instead of creating an object of a class to access those properties.

 

Static Variables Declaration

The following is the example of defining a class with static properties and those can be accessed directly with the type instead of a specific object name.

 

     class User

    {

        public static string name;

        public static string location;

        public static int age;

    }

From the above example, we defined variables with static keyword, we can then access those variables directly with a type name like User.name, User.location and User.age.

 

Below is the examples of how to access the variables directly with a type name in C#.

 

     Console.WriteLine(User.name);

            Console.WriteLine(User.location);

            Console.WriteLine(User.age);

 

The above statements, shows that we can access our static properties directly by using class name instead of with class instance using class and dot notation.

 

Generally, instance of a class will contain a separate copy of all instance fields so the memory consumption will increase automatically, but if we use static modifier there is only one copy of each field so automatically the memory will be managed efficiently.

 

We can use static modifier with classesmethods, properties, constructors, operators, fields and with events but it cannot be used with indexersfinalizers or types other than classes.

 

Static Keyword Example in C#

 

The following is the example for creating a class by including both static and non-static variables & methods. Here we can access non-static variables and methods by creating an instance of the class, but it is not possible for us to access the static fields with an instance of the class so the static variables and methods can be accessed directly with the class name.

 

using System;

namespace CsharpnaijaTutorial

{

    class User

    {

        // Static Variables

        public static string name, location;

        //Non Static Variable

        public int age;

        // Non Static Method

        public void Details()

        {

            Console.WriteLine("Non Static Method");

        }

        // Static Method

        public static void Details1()

        {

            Console.WriteLine("Static Method");

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            User user = new User();

            user.age = 32;

            user.Details();

            User.name = "Musa Gadabs";

            User.location = "Abuja";

 Console.WriteLine($"Name: {User.name}, Location: {User.location}, Age: {user.age}");

            User.Details1();

            Console.WriteLine("\nPress Enter Key to Exit..");

            Console.ReadLine();

        }

    }

 

}

 

From the above example, we created a class called “User” with static and non-static variables & methods. We are accessing non-static variables and methods with an instance of User class and static fields and methods are accessed directly with the class name (User).

 

Thank you

 

References

1.     Tutlane

2.     Guru99

 


Comments

Popular posts from this blog

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

Most Popular Programming Languages in 2020

Most Popular Programming Languages in 2020 In this blog post, you will learn about the most popular programming languages in 2020 for creating the best web applications. Check its pros and cons. Analyzed by technostacks Not very long ago, just a few people were considered to be computer programmers, and the general public viewed them with awe. In this digital age that we are now living in, however, a large number of IT jobs need a solid grasp of one or more programming languages. Whether one wants to develop a mobile app or get a certification for having programming knowledge, or even to learn new skills, one needs to opt for the right programming language. Below mentioned eight most popular programming languages which are in demand for software development and web applications. This is the most used programming languages in 2019 and will be in 2020. For each, there is little information about the language, benefits and its complexity, as well as about its usage. One must...

HashTable in C# with Example

  HashTable in C# with Example Hashtable  is used to store a collection of key/value pairs of different  data types  and are organized based on the hash code of the key.   Generally, the hashtable object will contain buckets to store elements of the collection. The bucket here, is a virtual subgroup of elements within the hashtable and each bucket is associated with a hash code, which is generated based on the key of an element.   In C#, hashtable is same as a  dictionary  object but the only difference is that the  dictionary  object is used to store a key-value pair of same  data type  elements.   When compared with  dictionary  object, the hashtable will provide a lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we are storing or retrieving values from the hashtable.   C# HashTable Declaration Hashtable is a non-generic type...