0

I have a type and some derived types. I wanna put names of this derived types in a ComboBox control in WPF. What is the right way to do this? Currently I'm using the Assembly namespace to get names of these types.

khrabrovart
  • 169
  • 1
  • 9
  • You have to use `Relections` do this. Do `Type superClass = myClass.GetType().BaseType` to get the base class name while enumerating in a list of types. if their base class name matches the one your are after, then get their names! very easy – Transcendent Oct 05 '14 at 19:49
  • @KingKing: Check out the updated comment – Transcendent Oct 05 '14 at 19:53
  • @KingKing: `Reflection` is a namespace, and what it does is to sneak into types. So any operation that is similar, even though can be done without using that namespace would be technically known as reflectioning. We also have it in Java – Transcendent Oct 05 '14 at 19:56

2 Answers2

4

You can use reflection to do this:

var type = typeof(SomeType);
IEnumerable<string> exporters = type.Assembly
    .GetTypes()
    .Where(t => t.IsSubclassOf(type))
    .Select(t => t.Name);

This would search for types only in the assembly which contains your source type

Pavel Krymets
  • 6,253
  • 1
  • 22
  • 35
4

The first step is to get a Type object for each of your derived types. Pavel's answer gives you a good base for that, though his solution only gives direct subtypes, not types further down the inheritance chain, and only types defined in the same assembly as the base type. Here's a slightly updated version:

var baseType = typeof(Base);
var currentlyLoadedAssemblies = AppDomain.Current.GetAssemblies();
var relevantTypes = currentlyLoadedAssemblies
       .SelectMany (assembly => assembly.GetTypes())
       .Where(type => baseType.IsAssignableFrom(type));
Types = relevantTypes.ToList();

No we have all the types, we can bind them to a WPF combobox. Rather than extracting the strings from the type names, we'll bind to the Type object itself, so when the user selects one, we'll have the selected Type object ready. We'll tell the ComboBox to display the Type's Name property.

public List<Type> Types {get;set;}
public Type SelectedType {get;set;}


<ComboBox ItemsSource="{Binding Types}" 
          SelectedItem="{Binding SelectedType}" 
          DisplayMemberPath="Name" />
Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63
  • And regarding interfaces - if the OP doesn't want interfaces and their implementations it's a simple fix to filter it out, but there's no reason to clutter the code with it for now. – Avner Shahar-Kashtan Oct 05 '14 at 20:31