Skip to content

Instantly share code, notes, and snippets.

@hodzanassredin
Created October 26, 2012 15:09
Show Gist options
  • Save hodzanassredin/3959323 to your computer and use it in GitHub Desktop.
Save hodzanassredin/3959323 to your computer and use it in GitHub Desktop.
first class properties
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FirstClassProperties
{
class Property<T, CONTAINERT>
{
T _val;
Func<T, CONTAINERT> _setter;
public Property(T val, Func<T, CONTAINERT> setter)
{
_val = val;
_setter = setter;
}
public T Get()
{
return _val;
}
public CONTAINERT Set(T val)
{
return _setter(val);
}
}
public static class PropertyCombinators
{
public static Property<Tuple<T,T2>, TCONTAINER> Combine<T, TCONTAINER,T2>(this Property<T, TCONTAINER> prop, Property<T2, TCONTAINER> prop2)
{
return new Property<Tuple<T,T2>,TCONTAINER>(new Tuple<T,T2>(prop.Get(), prop2.Get()), t => {
var i1 = prop.Set(t.Item1);
var i2 = prop2.Set(t.Item2);
return new Property<>()
});
}
}
class Person
{
public Person(int age, string name)
{
_age = age;
_name = name;
}
private readonly int _age;
private readonly string _name;
public Property<int, Person> Age()
{
return new Property<int, Person>(_age, x => new Person(x, _name));
}
public Property<string, Person> Name()
{
return new Property<string, Person>(_name, x => new Person(_age, x));
}
}
class Program
{
static void Main(string[] args)
{
var p = new Person(11, "hodza");
var age = p.Age().Get();
var p2 = p.Name().Set("hodza2");
var name2 = p2.Name().Get();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment