Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For what you're trying to do, I think the main benefit of using generics would be to take advantage of type inference. If you declare your method as follows :</p> <pre><code>public static string GetTag&lt;T&gt;(this HtmlHelper h, T myObj, TagBuilder tag) </code></pre> <p>You won't have to specify the type parameter when calling it, because it will be inferred from the usage (i.e. the compiler will see that the second parameter's type is <code>MyType</code>, so it will guess that T == MyType).</p> <p>But anyway, you don't really need to specify the type : the method could call <code>GetType</code> on the object, and use the resulting type the same way it would have used <code>typeof(T)</code>, so generics aren't so useful here.</p> <p>However, I see one reason to use them anyway : if you have an object of type <code>MySubType</code>, which inherits from <code>MyType</code>, you might want to render only properties defined in <code>MyType</code> : in that case you just have to specify <code>MyType</code> as the type parameter, overriding the type inference.</p> <p>Here's a possible implementation :</p> <pre><code>public static string GetTag&lt;T&gt;(this HtmlHelper h, T myObj, TagBuilder tag) { Type t = typeof(T); tag.Attributes.Add("class", t.Name); foreach (PropertyInfo prop in t.GetProperties()) { object propValue = prop.GetValue(myObj, null); string stringValue = propValue != null ? propValue.ToString() : String.Empty; tag.Attributes.Add(prop.Name, stringValue); } return tag.ToString(); } </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.
    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