Passing a Type to a Method and returning an instantiated object with additional Type member operations
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
using System; namespace AnnonymousTypeInstantiation { internal interface INamifiableEntity { void Namify(string suffix); } internal class Pet : INamifiableEntity { public string PetName { get; set; } public Pet() { } // required public void Namify(string name) { PetName = name; } } internal class User : INamifiableEntity { public string Name { get; set; } public User() { } // required public void Namify(string name) { Name = name; } } internal class Program { // The Static can be dropped private static T SetName<T>(string suffix) where T : INamifiableEntity, new() { var obj = new T(); obj.Namify(suffix); return obj; } static void Main(string[] args) { object obj1 = SetName<User>("stigzler"); object obj2 = SetName<Pet>("Fido"); Console.Write("User: " + ((User)obj1).Name + Environment.NewLine); Console.Write("Pet: " + ((Pet)obj2).PetName); Console.ReadLine(); } } } |