static void Main(string[] args) { dynamic person = new { Name = "Peter" }; var p = DuckType.As <IPerson>(person); Console.WriteLine(p.Name); }
[Ignore] //Manual test public void As_Loop() { foreach (object obj in GetObjects()) { Assert.IsNotNull(DuckType.As <IHasValue>(obj).Value); } }
public void As_Invalid() { string expected = Guid.NewGuid().ToString(); BespokeString bespoke = new BespokeString(expected); Assert.IsNotInstanceOfType(bespoke, typeof(IHasValue)); IHasValue duck = DuckType.As <IHasValue>(bespoke); Assert.IsNull(duck); }
public void As_Struct() { int expected = _random.Next(); BespokeInt bespoke = new BespokeInt(expected); Assert.IsNotInstanceOfType(bespoke, typeof(IHasValue)); IHasValue duck = DuckType.As <IHasValue>(bespoke); Assert.IsInstanceOfType(duck, typeof(IHasValue)); Assert.AreEqual(expected, duck.Value); }
public void As() { DateTime expected = new DateTime(_random.Next(1900, 2000), _random.Next(1, 12), _random.Next(1, 28)); BespokeDateTime bespoke = new BespokeDateTime(expected); Assert.IsNotInstanceOfType(bespoke, typeof(IHasValue)); IHasValue duck = DuckType.As <IHasValue>(bespoke); Assert.IsInstanceOfType(duck, typeof(IHasValue)); Assert.AreEqual(expected, duck.Value); }
/// <summary> /// Returns the object, duck-typed to the given interface /// </summary> /// <typeparam name="TInterface"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static TInterface As <TInterface>(this object obj) { return(DuckType.As <TInterface>(obj)); }