Using the AWS InstanceType Properties in a C# DropDownCombo
To read out the static properties from the AWS SDK InstanceType class in order to get the AWS instance type names
Introduction
The InstanceType
class has properties representing the names of each type of instance you can launch on AWS. Instead of hard-coding these names into your code, you can iterate through the InstantType
class and fill a ComboBox
with these names.
Background
Many would maybe start out by doing this:
foreach (var property in InstanceType.GetType().GetProperties())
{
Console.WriteLine(property.Name);
}
Since a static
class cannot be instantiated (in this case, the class is InstanceType
), the solution calls for a slightly different approach.
Practical Example
Populate a ComboBox
with InstanceType
constants:
// InstanceType is class with static properties
Type type = typeof(InstanceType);
foreach (var instType in type.GetFields
(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public))
{
var typeName = instType.GetValue(null); // We can't pass static classes
// as objects into this,
// so null is passed instead
ComboItem item = new ComboItem()
{ Text = typeName.ToString(), Value = typeName.ToString() };
TypeSelectorCombo.Items.Add(item);
}
public class ComboItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
Here, I have also made a class named ComboItem
, just to make it easier to populate the ComboBox
control in a Windows Forms project for instance.
And... that's about it. Not the diamond of tips, but it will most certainly save some campers a lot of agony.