Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/whiteblackgoose/csharpoption

Success/Maybe/Option/etc. type for C#, easy to use and cheap and etc.
https://github.com/whiteblackgoose/csharpoption

Last synced: 18 days ago
JSON representation

Success/Maybe/Option/etc. type for C#, easy to use and cheap and etc.

Awesome Lists containing this project

README

        

> **WARNING**: Deprecated.
>
> Use [Honk#](https://github.com/WhiteBlackGoose/HonkSharp) instead.

## Option for C\#

Imagine using the `TryPattern` in 2021... compare this old-fashioned ugly bruuh
```cs
if (!...TryDo(..., out var res))
return "Invalid";
if (res.Property > 0 and res.Property < 6)
return res.ToString();
else
return "Quack";
```
to this nice cool awesome
```cs
return Do(...) switch
{
Success({ Property: > 0 and < 6 } res) => res.ToString(),
Success => "Quack",
_ => "Invalid"
};
```

### TryParse

With
```cs
static Success? Parse(string? s)
=> int.TryParse(s, out var res) ? new(res) : null;
```
You now can write
```cs
Console.WriteLine(
Parse(Console.WriteLine()) switch
{
Success(> 6) => $"Value is valid and greater than 6",
Success => "Value is valid",
var Failure => "Invalid value"
}
);
```

### TryGet

Also, you can now use `null` as a valid type. With
```cs
public static class Extensions
{
public static Success? Get(this Dictionary dic, TKey key)
=> dic.TryGetValue(key, out var res) ? new(res) : null;
}
```
You can now write
```cs
var dict = new Dictionary { { "key", null } };
Console.WriteLine(
dict.Get("key") switch
{
Success(null) => "Got a valid null",
Success(var notNull) => $"Got a valid notnull: {notNull}",
_ => "Got invalid"
}
);
```