Search code examples
c#constants

Since System.Half is not a primitive, how can I make a const of it?


The rather new-ish System.Half is not a primitive so you can't make a compile time const of it to use as an optional arg. Currently there's discussion of making it a primitive in a later C# release, but it hasn't happened yet. Is there some work around to do something like this?:

// This gets the compile error: The type 'Half' can't be declared const
const Half MyVal = 42; 

void MyMethod(Half myArg = MyVal)
{
    ...
}

Solution

  • You can try using readonly instead of const, something like this:

    // Unlike const, readonly will be computed in run time
    static readonly Half MyVal = (Half)42; 
    
    // Since MyVal is not a const we can't use it in the declaration ...
    void MyMethod(Half myArg)
    {
        ...
    }
    
    // ... but we can use myArg in the overload 
    void MyMethod() => MyMethod(MyVal);
    

    Fiddle