Skip to content

Instantly share code, notes, and snippets.

@hagbarddenstore
Last active December 20, 2015 20:39
Show Gist options
  • Save hagbarddenstore/6192347 to your computer and use it in GitHub Desktop.
Save hagbarddenstore/6192347 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
public interface A
{
}
public abstract class BaseA : UserControl, A
{
}
[System.ComponentModel.DataAnnotations.Display(Name = "B")]
public class B : BaseA
{
}
[System.ComponentModel.DataAnnotations.Display(Name = "C")]
public class C : BaseA
{
}
public class MainForm
{
private readonly Dictionary<string, Type> _types = new Dictionary<string, Type>();
private UserControl _myControl;
private void Initialize()
{
var types = GetTypes();
foreach (var type in types)
{
var name = GetName(type);
_types.Add(name, type);
// Add to your menu
}
}
private static string GetName(Type type)
{
var attribute = type.GetCustomAttributes()
.Where(x => x is System.ComponentModel.DataAnnotations.DisplayAttribute)
.FirstOrDefault();
return attribute == null ? type.Name : attribute.Name;
}
private static IEnumerable<Type> GetTypes()
{
var types = typeof(MainForm).Assembly.GetTypes()
.Where(x => !x.IsAbstract && x.IsClass && typeof(BaseA).IsAssignableFrom(x))
.ToList();
return types;
}
private void MyOnMenuClick(object sender, EventArgs args)
{
// Find out which button got clicked, which name it has.
var name = "";
var type = _types[name];
var instance = (BaseA)Activator.CreateInstance(type);
// Dispose the old control
_myControl.Dispose();
_myControl = instance;
// Time to start displaying the new control
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment