Julian Gonzalez

Generation

generate functionThu, 30 Mar 2023

How to return a generic object in c# create objects and implement interface

interface IAnimal { void Breathe(); } class Dog : IAnimal { public void Breathe() { Console.WriteLine("I'm breathing"); } } class Cat : IAnimal { public void Breathe() { Console.WriteLine("I'm breathing"); } } class Program { static void Main(string[] args) { IAnimal dog = GetAnimal(args[0]); dog.Breathe(); IAnimal cat = GetAnimal(args[0]); cat.Breathe(); Console.ReadLine(); } private static IAnimal GetAnimal(string animal) { if (animal == "dog") { return new Dog(); } return new Cat(); } }

Questions about programming?Chat with your personal AI assistant