Created
October 26, 2012 15:09
-
-
Save hodzanassredin/3959323 to your computer and use it in GitHub Desktop.
first class properties
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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