FooBar Factory

CSharp · Console

/Program.cs

using System;
using System.Linq;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		var fooBars = FooBarizableFactory.GetFooBars(typeof(Foo));
		
		foreach( var fb in fooBars)
			Console.WriteLine(fb.GetType());
	}
}


public abstract class FooBarizable{

    public string Name { get; set; }
    //No need for method here, interface will enforce it exists
	
}

public class Foo : FooBarizable{
	public int FooInt { get; set; }
}

public class Bar : FooBarizable{
	public string BarString { get; set; }
}

public static class FooBarizableFactory {
	
	public static IEnumerable<FooBarizable> GetFooBars(Type type){
		var parentType = typeof(FooBarizable);
		
		if (!parentType.IsAssignableFrom(type))
			throw new ArgumentException("Not a FooBarizable");					
		
		switch(type.Name) {
			case "Foo":
				return new List<Foo>() { new Foo () };
			
			case "Bar":
				return new List<Bar>() { new Bar() };
			
			default:
				throw new ArgumentException("Not a known FooBarizable");
		}
	}
}
;