Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A struct is a single entity, not a collection of variables. This means that you can't 'iterate' over its properties. What you need to do is get a collection of the property names and iterate over it. Your GetName function can't do this because it just returns the name of the first property.</p> <p>To add the property names to a combo all you have to do is:</p> <pre><code> var vars = new msgVars(); foreach(var name in GetNames(vars)) comboBox1.Items.Add(name); </code></pre> <p>In fact, getting the property name is so easy that you could get rid of GetNames completley and just write</p> <pre><code> foreach (var prop in typeof(msgVars).GetProperties()) comboBox1.Items.Add(prop.Name); </code></pre> <p>There are various ways you can write GetNames to return a collection of names. You can fill a List with the property names although the simplest is to have it return an iterator like this:</p> <pre><code> public static IEnumerable&lt;string&gt; GetNames&lt;T&gt;(T obj) where T:struct { var properties = typeof (T).GetProperties(); foreach (var propertyInfo in properties) { yield return propertyInfo.Name; } } </code></pre> <p>Finally, you don't really need to pass an instance of your struct to the method, as you are enumerating the structs property names, not their values. You can rewrite GetNames like this</p> <pre><code> public static IEnumerable&lt;string&gt; GetNames&lt;T&gt;() where T:struct { var properties = typeof (T).GetProperties(); foreach (var propertyInfo in properties) { yield return propertyInfo.Name; } } </code></pre> <p>and load the names like this</p> <pre><code> foreach(var name in GetNames&lt;msgVars&gt;()) comboBox1.Items.Add(name); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload