meetings/working-groups/discriminated-unions/DU-2022-10-19.md
The theme of our first meeting was collecting scenarios that we think can be improved by discriminated unions, so we have an idea of what problems we're trying to solve.
public enum PageState
{
NotLoaded,
Loading,
Loaded,
Errored
}
public class Page {
PageState state;
// used when state is Loaded
PageData data;
// used when state is Errored
string errorMessage;
public View Render() {
switch (this.state)
{
case PageState.NotLoaded:
return ShowLoadButton();
case PageState.Loading:
return ShowLoadingSpinner();
case PageState.Loaded:
return ShowData(this.data!);
case PageState.Errored:
return ShowErrorMessage(this.errorMessage);
default:
throw Unreachable;
}
}
}
class PageData { }
class View { }
throw Unreachable;PageState.Show()?
[HttpGet(Name = "GetWeatherForecast")]
public IActionResult Get(int id)
{
return id % 2 == 0
? Ok(Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}).ToArray())
: NotFound();
}
app.MapGet("/minimal-dus/{id}", Results<Ok<string>, ProblemHttpResult> (int id) => {
return id % 2 == 0
? TypedResults.Ok("Valid ID")
: TypedResults.Problem("Invalid Id");
});
IActionResult is very common in MVC
Results<TypeA, TypeB, ... TypeN> (lots of versions of this, like ValueTuple)
IResultsOptional or Result<TOk, TErr>Optional<T> in the BCL? in Rust.
For next time, we will look at the commonalities in these scenarios and start looking at strategies for representing them.