Skip to content

Instantly share code, notes, and snippets.

@ilkerde
Created August 26, 2011 14:39
Show Gist options
  • Save ilkerde/1173541 to your computer and use it in GitHub Desktop.
Save ilkerde/1173541 to your computer and use it in GitHub Desktop.
A quick prototype for a shallow copy of an object with changing values ;-)
add-type @"
using System;
using System.Linq;
public class A {
public A() { Age = 40; Name = "DerAlbert"; Type = "Original"; }
public int Age { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public A With(object o) {
var matches = from otherProperty in o.GetType().GetProperties()
join myProperty in typeof(A).GetProperties() on otherProperty.Name equals myProperty.Name
select new { Mine = myProperty, Yours = otherProperty };
A clone = this.MemberwiseClone() as A;
foreach (var match in matches)
match.Mine.SetValue(clone, match.Yours.GetValue(o, null), null);
return clone;
}
}
public class O {
public O() { Age = 30; Name = "forki"; Type = "Funky"; }
public int Age { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
public static class Testing {
public static A Anonymous() {
A a = new A();
return a.With(new {Name = "ilkerde", Age = 35, Type = "Dynamic"});
}
}
"@ -lang csharpversion3
$o = new-object O
$a = new-object A
# @forki: is it that what you wanted? ;-)
$b = $a.With($o)
$c = [Testing]::Anonymous();
$a
$b
$c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment