Static member variables

In this section, we will look at how we can use the Static keyword against a class and its member variables. In the following code example, we have created a Static class called Configuration. Just for the sake of explanation, we will not be using the Static keyword for a member variable present in it:

internal static class Configuration
{
public string ConnectionString;
}

Let's try to compile the program. We get an error stating that the ConnectionString member variable must be declared static as well:

Once we use the static keyword against the ConnectionString member variable as well, the error goes away. This is the correct representation of the class:

internal static class Configuration
{
public static string ConnectionString;
}

If we need to use Set/Get value in the member variable, we can access it directly by using the name of the class. Here is the code snippet for this:

Configuration.ConnectionString = "Sample Connection String";

In the preceding code example, we had a Static class Configuration in which it was mandatory to have the static modifier against all of the member variables and properties. However, there could be some circumstances when we don't want the entire class to be static but just a particular member variable present inside it. 

We can achieve this in C# by using the static modifier not against the class but against the particular member variable. If we need to use this in the preceding code, the following would be the updated code:

internal class Configuration
{
public static string ConnectionString;
}

However, there will be no change in the way we access this property. It can still be done by using the name of the class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.144.59