Is there a C# equivalent for TypeScript's never type? I am curious about this.
For example, in TypeScript, if I write the following code, I will get a build time error:
enum ActionTypes {
Add,
Remove
}
type IAdd = {type: ActionTypes.Add};
type IRemove = {type: ActionTypes.Remove};
type IAction = IAdd | IRemove;
const ensureNever = (action: never) => action;
function test(action: IAction) {
switch (action.type) {
case ActionTypes.Add:
break;
default:
ensureNever(action);
break;
}
}
The error message will be:
Argument of type 'IRemove' is not assignable to parameter of type 'never'.
The never type in TypeScript is very useful to ensure that all cases are handled when a logic is changed in one file.
I have been searching for a similar feature in C#, but I have not found anything yet.
Here is my attempt at replicating this behavior in C#:
using System;
class Program
{
private enum ActionTypes
{
Add,
Remove
}
interface IAction {
ActionTypes Type { get; }
}
class AddAction : IAction
{
public ActionTypes Type
{
get {
return ActionTypes.Add;
}
}
}
class RemoveAction : IAction
{
public ActionTypes Type
{
get
{
return ActionTypes.Remove;
}
}
}
static void Test(IAction action)
{
switch (action.Type)
{
case ActionTypes.Add:
Console.WriteLine("ActionTypes.Add");
break;
default:
// what should I put here to be sure its never reached?
Console.WriteLine("default");
break;
}
}
static void Main(string[] args)
{
var action = new RemoveAction();
Program.Test(action);
}
}
I am looking for a way to generate a build time error, similar to what happens in TypeScript, rather than having issues at runtime.