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

87 Views Asked by At

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)
{
    ...
}
1

There are 1 best solutions below

0
Dmitry Bychenko On BEST ANSWER

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