Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@janderit
Created October 15, 2016 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janderit/379415f23ec3da9a362e344416f8b32c to your computer and use it in GitHub Desktop.
Save janderit/379415f23ec3da9a362e344416f8b32c to your computer and use it in GitHub Desktop.
Devopenspace: Demo Code aus der C# Session 10:30
using System;
using System.Collections.Generic;
namespace Sandbox
{
class Program
{
public Program()
{
Readonly_mit_Field = 5;
}
public int Express => 5;
public int Readonly {get { return 5; } }
public int Readonly_mit_Field_nur_aus_ctor { get; }
public int Readonly_mit_Field { get; private set; }
public void Dummy()
{
Readonly_mit_Field = 42;
}
static void Main(string[] args)
{
}
private Dictionary<int, User> _users = new Dictionary<int, User>();
public Optional<User> GetUserById(int id)
{
return _users.Retrieve(id);
}
public void Demo()
{
Optional<User> user = GetUserById(42);
Console.Out.WriteLine(
user
.Select(_ => _.Name)
.ValueOr("-nicht gefunden-"));
}
}
public struct User
{
public User(string name, Guid id)
{
Name = name;
Id = id;
}
public readonly string Name;
public readonly Guid Id;
}
public struct Optional<T>
{
public Optional(T value)
{
_value = value;
HasValue = true;
}
public readonly bool HasValue;
private readonly T _value;
internal T Value
{
get
{
if (!HasValue) throw new InvalidOperationException("Kein Wert");
return _value;
}
}
}
public static class Extensions
{
public static Optional<TValue> Retrieve<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key)
{
return dict.ContainsKey(key) ? new Optional<TValue>(dict[key]) : new Optional<TValue>();
}
public static Optional<TOut> Select<TIn, TOut>(this Optional<TIn> option, Func<TIn, TOut> map)
{
if (option.HasValue) return new Optional<TOut>(map(option.Value));
return default(Optional<TOut>);
}
public static T ValueOr<T>(this Optional<T> option, T default_to)
{
return option.HasValue ? option.Value : default_to;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment