Visual Studio .NET - what the use static keyword

Asked By aman on 09-Sep-11 01:27 AM
hi all,
what the use static keyword?
thanks
Reena Jain replied to aman on 09-Sep-11 01:31 AM
hi,

First, the static keyword in the C# language describes a member such as a field, property or method that is part of a type, not an instance of the type. The static keyword was mainly chosen for historical reasons as it was used in C and C++. The program here contains two files: first a file that contains the global variables in a public static class, and then the Program.cs file that uses the global class.
// Global variables class (GlobalVar.cs, C#)
 
/// <summary>
/// Contains global variables for project.
/// </summary>
public static class GlobalVar
{
  /// <summary>
  /// Global variable that is constant.
  /// </summary>
  public const string GlobalString = "Important Text";
 
  /// <summary>
  /// Static value protected by access routine.
  /// </summary>
  static int _globalValue;
 
  /// <summary>
  /// Access routine for global variable.
  /// </summary>
  public static int GlobalValue
  {
  get
  {
    return _globalValue;
  }
  set
  {
    _globalValue = value;
  }
  }
 
  /// <summary>
  /// Global static field.
  /// </summary>
  public static bool GlobalBoolean;
}
 
~~~ Program that uses global variables (Program.cs, C#) ~~~
 
using System;
 
class Program
{
  static void Main()
  {
  // Write global constant string.
  Console.WriteLine(GlobalVar.GlobalString);
 
  // Set global integer.
  GlobalVar.GlobalValue = 400;
 
  // Set global boolean.
  GlobalVar.GlobalBoolean = true;
 
  // Write the two previous values.
  Console.WriteLine(GlobalVar.GlobalValue);
  Console.WriteLine(GlobalVar.GlobalBoolean);
  }
}
 
//out put
 
Important Text
400
True

hope this will help you
Web Star replied to aman on 09-Sep-11 01:38 AM
In oneline you can say
"Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. "

The main features of a static class are:

  • They only contain static members.

  • They cannot be instantiated.

  • They are sealed.

  • They cannot contain http://msdn.microsoft.com/en-us/library/k6sa6h87(v=vs.80).aspx

    The reason one would use a "created" Singleton as opposed to a static class, is when resources that are expensive need to be released as 
    soon as they are finished with whereas, with a static class, any state fields are kept in memory until the program quits.

The key thing to remember about "static" is that fields in a class marked static, or static methods of a class that deal with such fields, introduce a condition of non thread safety. The method itself, as long as it does not deal with static fields in the class, is perfectly threadsafe.

The advantage of using the static class is that compiler can check that no instance of the class is accidentally added. The complier will not allow any instance class of a static class. We also cannot inherit a static class since it is sealed. Static class do not have constructor, but can still declare static constructor to set up the initial values.

Static class also makes the implementation simpler and faster since we do not have make and instance of the class to call its method.  An example of good use of static class would be a class like math, which does all the mathematic function, or a currency converter class to convert currency class for converting the currency

see example of static class and member

public static class TemperatureConverter
{
    public static double CelsiusToFahrenheit(string temperatureCelsius)
    {
        // Convert argument to double for calculations.
        double celsius = System.Double.Parse(temperatureCelsius);

        // Convert Celsius to Fahrenheit.
        double fahrenheit = (celsius * 9 / 5) + 32;

        return fahrenheit;
    }

    public static double FahrenheitToCelsius(string temperatureFahrenheit)
    {
        // Convert argument to double for calculations.
        double fahrenheit = System.Double.Parse(temperatureFahrenheit);

        // Convert Fahrenheit to Celsius.
        double celsius = (fahrenheit - 32) * 5 / 9;

        return celsius;
    }
}

class TestTemperatureConverter
{
    static void Main()
    {
        System.Console.WriteLine("Please select the convertor direction");
        System.Console.WriteLine("1. From Celsius to Fahrenheit.");
        System.Console.WriteLine("2. From Fahrenheit to Celsius.");
        System.Console.Write(":");

        string selection = System.Console.ReadLine();
        double F, C = 0;

        switch (selection)
        {
            case "1":
                System.Console.Write("Please enter the Celsius temperature: ");
                F = TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine());
                System.Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
                break;

            case "2":
                System.Console.Write("Please enter the Fahrenheit temperature: ");
                C = TemperatureConverter.FahrenheitToCelsius(System.Console.ReadLine());
                System.Console.WriteLine("Temperature in Celsius: {0:F2}", C);
                break;

            default:
                System.Console.WriteLine("Please select a convertor.");
                break;
        }
    }
}

smr replied to aman on 09-Sep-11 01:39 AM
HI

The static part holds the �static� member variables and methods. What exactly is static? Those methods and variables which don't need an instance of a class to be created are defined as being static. In C# (and Java too), we use the static keyword to label such members as static. For e.g.:

refer
http://www.codeproject.com/KB/cs/codeconcepts.aspx
dipa ahuja replied to aman on 09-Sep-11 12:32 PM
What is Static Keyword:

A static field belongs to the class itself, and is shared among all instances of that class. Changes made from instance A will be visible immediately to instances B and C if they access the field.