简体   繁体   中英

What is the real difference between a static member and a constant in C#?

I'm learning C#,and now i'm trying to understand static members and constants.Which is the best way to declare a constant? This way?

class Myclass
{
    public const double G=9.8;
}

Or

   class Myclass
    {
        private static double G{get;set;}
        static MyClass()
        {
            G=9.8;
        }
    }

I've asked this question because,with the 2 ways i access the membre with the same code:

Console.WriteLine(Myclass.G);

constant :

Constant fields are defined at the time of declaration in the code snippet, because once they are defined they can't be modified. By default a constant is static, so you can't define them static from your side.

It is also mandatory to assign a value to them at the time of declaration otherwise it will give an error during compilation of the program snippet. That's why it is also called a compile-time constant.

Explanation:

Consider ff. code:

void Sum(int j)  
{  
  const int i = 9, k = 2;  
  const int A = i + k;  
} 

This will produce a result of 11, without showing any error since we already declared it at the initial point of declaration.

But how about:

void Sum(int j)  
{  
   const int i = 9, k = 2;  
  //const int A = i + k;  
   Const int B = i + j;  
} 

This code snippet will take you toward a compile-time error, because there is no initialization, since it's evaluated at run time.

Points to Remember

  • Compile-time constant
  • Can't be declared static
  • Can't be modified or changed
  • Can be of any type of Access Modifier
  • Local scope
  • Needs to get initialized
  • Declared at the time of declaration

Static

The static keyword is used to declare a static member. If we are declare a class as a static class then in this case all the class members must be static too. The static keyword can be used effectively with classes, fields, operators, events, methods and so on effectively.

Consider ff. code:

class ReadOnly  
{  
    static int i = 11;  
    public static void disp()  
    {  
        Console.WriteLine(i);
    }  
}

Explanation:

This code will show no error and produce a result (11), since we declared its value to be static at the time of declaration. So we can access it depending on our use in the program.

But how about this:

class ReadOnly  
{  
    int i = 9;  
    public static void disp()  
    {  
        Console.WriteLine(i);  
    }  
}

This snippet above will show an error, because we didn't declare a value for the static and we are trying to access it within a method. We can't do that.

Points to Remember:

  • Can't be used with indexers
  • Works with constructors too
  • By default it is private
  • Can be parameterized or public too
  • If its applied to a class then all the class members need to be static

You can read more about above explanation here: constant vs readonly vs static

Additional note for static methods.

Consider ff. code:

public class SomeClass {
    public string SomeMethod() {
      return "Hello, World.";
    }
}

When you want to Access SomeMethod of SomeClass , you need to instantiate SomeClass first:

var some = new SomeClass();
string result = some.SomeClass(); //this will set result as "Hello, World."

Compared to a static method:

public class SomeClass {
    public static string SomeMethod() {
      return "Hello, World.";
    }
}

When accessing SomeMethod , you don't need to instantiate SomeClass . You can access it directly by:

string result = SomeClass.SomeMethod(); //this will give "Hello, World."

Which is the best way to declare a constant?

Its not the best, its the only way : const double G = 9.8; .

Or (...) static double G { get; set; } static double G { get; set; }

Thats not a constant! Constant means constant : 1 is a constant, 'c' is a constant, PI is a constant... they represent values that don't change , ever! . Your second implementation of G can change, therefore its not a constant.

Also, its important you notice that constants are known at compile time , there is no evaluation needed at runtime.

This is the reason why any reference type const (expect string which has specific compiler support through string literals ) can only be initialized to null , any other option would need to be evaluated at runtime.

Its also the reason why only a finite set of value types can be declared as const too. All of them are existing types in the framework and.. surprise, surprise, they all have compiler literal constant support: 1 , 'c' , 9.8 or 0.25M but not 01/01/2017 (how else would the compiler know the values before runtime?).

Another interesting question you didn't make is: what about static readonly ?

You can think of static readonly as "the poor man's" const . Its often used to circumvent the limitations const offers concerning what types and initializing values are allowed.

It is almost the same as a constant, but there are a few important and decisive differences:

  1. It can change; although it is readonly , you can change it's value inside the static constructor of the declaring type. const can never change after initialized.
  2. It is evaluated at runtime , not compile time as a true const .
  3. Any type can be declared as a static readonly and initialized to any valid value as you would do with any regular field.

As a nittpicking side note, you shouldn't make G a constant ;). It changes, and quite a bit. G in Ecuador is different from G in the North Pole.

const variables are assigned values at time of definition.

They are available at compile time. You can even use a compile time evaluate-able expression at compile time. But once a value has been assigned to a const variable, it cannot be changed at any other time.

Using static field means the value will remain same for every user of the application, but this value can be changed by code in any of the classes, and it will change for every user of the application.

Do not use static for constants, use const only. const are by default static, and you cannot use static keyword with it.

Check this

void Main()
{
 // You will not be able to change value for const variable.
 Console.WriteLine(Myclass.G);

  // You will be able to change value for static variable, 
 // and this change will impact all users of the application.
 //  For every user, this field will store value of 10 now. 
 // That will not be required or desired code behavior.
 Myclass1.G = 10;
 Console.WriteLine(Myclass1.G);
}

// Normal class with const field 
class Myclass
{
    public const double G=9.8;
}

 //static class with static constructor
 static class Myclass1
    {
        public static double G{get;set;}
        static Myclass1()
        {
            G=9.8;
        }
    }

Read More

Here you are talking about two different things, and this is their definition from MSDN:

1- static modifier : To declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, finalizers, or types other than classes.

2- const keyword : To declare a constant field or a constant local. Constant fields and locals aren't variables and may not be modified. Constants can be numbers, Boolean values, strings, or a null reference. Don't create a constant to represent information that you expect to change at any time.

So a static member is defined for a Class (for all its instances, and that's why you can access it directly from the name of the Class) but can be modified. a const field of class can not be modified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM