C# difference between const int, const someStruct. Why is const someStruct not "compile-time constant"?

StackOverflow https://stackoverflow.com/questions/22420172

  •  15-06-2023
  •  | 
  •  

質問

const Vector4 colorBlack = new Vector4(0,0,0,1);//Vector4 is struct
public static void example(Vector4 color = colorBlack) //not ok
{
   //do something
}
const int someInt = 0;
public static void exampleInt(int n = someInt) // ok
{

}

I want know what exactly "compile-time constant" is. From here it states

It just means that every instance of the member marked as const will be replaced with its value during compilation, while readonly members will be resolved at run-time.

So I assumed if I had my colorBlack as const, then it will be compile-time constant, but compiler tells me otherwise. But it doesn't complain about "const int some int = 0;" being compile-time constant.

Why?

役に立ちましたか?

解決

See Can I specify a default Color parameter in C# 4.0?

Also: Default arguments for structures

As described in Section 7.15, a constant-expression is an expression that can be fully evaluated at compile-time. Since the only way to create a non-null value of a reference-type other than string is to apply the new operator, and since the new operator is not permitted in a constant-expression, the only possible value for constants of reference-types other than string is null.

In other words, at compile time, you can only default to:

  • null
  • a literal string
  • new T() // no arguments, or equivalently default(T)

Since you can only use new if you are using default arguments, and you can't do that with a reference type (struct) and because you need to specify some specific arguments anyway, you're only option is to pass null.

const Vector4 colorBlack = new Vector4(0,0,0,1);  // Vector4 is struct
public static void example(Vector4? color = null) // ? makes it nullable
{
    if (color == null)
        color = colorBlack;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top