Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First of all, if you want to access the properties of a type, ensure you are using a type which has properties:</p> <pre><code>public class User { public string Name{get;set;} public int Number{get;set;} public Address Address{get;set;} } public class Address { public string Street{get;set;} public string State{get;set;} public string Country{get;set;} } </code></pre> <p>Second, <code>prp.GetType()</code> will always return <code>PropertyInfo</code>. You are looking for <code>prp.PropertyType</code>, which will return the Type of the property.</p> <p>Also, <code>if(!prp.GetType().IsPrimitive &amp;&amp; prp.GetType().IsClass)</code> won't work the way you want, because <code>String</code> e.g. is a class and also not a primitive. Better use <code>prp.PropertyType.Module.ScopeName != "CommonLanguageRuntimeLibrary"</code>.</p> <p>Last but not least, to use recursion, you actually have to put your code into a method.</p> <p>Here's a complete example:</p> <pre><code>IEnumerable&lt;string&gt; GetPropertInfos(object o, string parent=null) { Type t = o.GetType(); PropertyInfo[] props = t.GetProperties(BindingFlags.Public|BindingFlags.Instance); foreach (PropertyInfo prp in props) { if(prp.PropertyType.Module.ScopeName != "CommonLanguageRuntimeLibrary") { // fix me: you have to pass parent + "." + t.Name instead of t.Name if parent != null foreach(var info in GetPropertInfos(prp.GetValue(o), t.Name)) yield return info; } else { var value = prp.GetValue(o); var stringValue = (value != null) ? value.ToString() : ""; var info = t.Name + "." + prp.Name + ": " + stringValue; if (String.IsNullOrWhiteSpace(parent)) yield return info; else yield return parent + "." + info; } } } </code></pre> <p>Used like this:</p> <pre><code>var user = new User { Name = "Foo", Number = 19, Address = new Address{ Street="MyStreet", State="MyState", Country="SomeCountry" } }; foreach(var info in GetPropertInfos(user)) Console.WriteLine(info); </code></pre> <p>it will output</p> <pre><code>User.Name: Foo User.Number: 19 User.Address.Street: MyStreet User.Address.State: MyState User.Address.Country: SomeCountry </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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