Static readonly vs const

2018-12-31 06:19发布

I've read around about const and static readonly fields. We have some classes which contains only constant values. Used for various things around in our system. So I am wondering if my observation is correct:

Should these kind of constant values always be static readonly for everything that is public? And only use const for internal/protected/private values?

What do you recommend? Should I maybe even not use static readonly fields, but rather use properties maybe?

标签: c# constants
15条回答
大哥的爱人
2楼-- · 2018-12-31 06:57

I would use static readonly if the Consumer is in a different assembly. Having the const and the Consumer in two different assemblies is a nice way to shoot yourself in the foot.

查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 07:03

Constants are like the name implies, fields which don't change and are usually defined statically at compile time in the code.

Read only variables are fields that can change under specific conditions.

They can be either initialized when you first declare them like a constant, but usually they are initialized during object construction inside the constructor.

They cannot be changed after the initialization took place, in the conditions mentioned above.

Static read-only sounds like a poor choice to me since, if it's static and it never changes, so just use it public const, if it can change then it's not a constant and then, depending on your needs, you can either use read-only or just a regular variable.

Also, another important distinction is that a constant belongs to the class, while the read-only variable belongs to the instance!

查看更多
还给你的自由
4楼-- · 2018-12-31 07:04

This is just a supplement to the other answers. I will not repeat them (now four years later).

There are situations where a const and a non-const have different semantics. For example:

const int y = 42;

static void Main()
{
  short x = 42;
  Console.WriteLine(x.Equals(y));
}

prints out True, whereas:

static readonly int y = 42;

static void Main()
{
  short x = 42;
  Console.WriteLine(x.Equals(y));
}

writes False.

The reason is that the method x.Equals has two overloads, one that takes in a short (System.Int16) and one that takes an object (System.Object). Now the question is whether one or both apply with my y argument.

When y is a compile-time constant (literal), the const case, it becomes important that there does exist an implicit conversion from int to short provided that the int is a constant, and provided that the C# compiler verifies that its value is within the range of a short (which 42 is). See Implicit constant expression conversions in the C# Language Specification. So both overloads have to be considered. The overload Equals(short) is preferred (any short is an object, but not all object are short). So y is converted to short, and that overload is used. Then Equals compares two short of identical value, and that gives true.

When y is not a constant, no implicit conversion from int to short exists. That's because in general an int may be too huge to fit into a short. (An explicit conversion does exist, but I didn't say Equals((short)y), so that's not relevant.) We see that only one overload applies, the Equals(object) one. So y is boxed to object. Then Equals is going to compare a System.Int16 to a System.Int32, and since the run-time types do not even agree, that will yield false.

We conclude that in some (rare) cases, changing a const type member to a static readonly field (or the other way, when that is possible) can change the behavior of the program.

查看更多
看淡一切
5楼-- · 2018-12-31 07:04

The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants

Short and clear MSDN reference here

查看更多
墨雨无痕
6楼-- · 2018-12-31 07:05

public static readonly fields are a little unusual; public static properties (with only a get) would be more common (perhaps backed by a private static readonly field).

const values are burned directly into the call-site; this is double edged:

  • it is useless if the value is fetched at runtime, perhaps from config
  • if you change the value of a const, you need to rebuild all the clients
  • but it can be faster, as it avoids a method call...
  • ...which might sometimes have been inlined by the JIT anyway

If the value will never change, then const is fine - Zero etc make reasonable consts ;p Other than that, static properties are more common.

查看更多
何处买醉
7楼-- · 2018-12-31 07:05

Const : const variable values have to define along with declaration and after that it won't change.const are implicitly static so without creating class instance we can access them. this has a value at compile time

ReadOnly: readonly variable values we can define while declaring as well as using the constructor at runtime. readonly variables cant access without class instance.

Static readonly: static readonly variable values we can define while declaring as well as only through static constructor but not with any other constructor.these variables also we can access without creating class instance(As static variables).

static readonly will be better choice if we have to consume the variables in different assemblies.Please check the full details in below link

https://www.stum.de/2009/01/14/const-strings-a-very-convenient-way-to-shoot-yourself-in-the-foot/

查看更多
登录 后发表回答