Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can detect if an object has a property without having to use the dynamic features of C# 4.0 - instead using the reflection features that have been around for a while (I know at least .NET 2.0, not sure about &lt; 2.0)</p> <pre><code>PropertyInfo info = codeObject.getType().GetProperty( "LinePragma", BindingFlags.Public | BindingFlags.Instance ) </code></pre> <p>If it the object does not have the property, then GetProperty() will return null. You can do similar for fields ( GetField() ) and methods ( GetMethod() ).</p> <p>Not only that, but once you have the PropertyInfo, you can use it directly to do your set:</p> <pre><code>info.SetValue(codeObject, new CodeLinePragma(), null); </code></pre> <p>If you're not sure whether the property has a set method, you could take the even safer route:</p> <pre><code>MethodInfo method = info.GetSetMethod(); if(method != null) method.Invoke(codeObject, new object[]{ new CodeLinePragma() }); </code></pre> <p>This also gives you the added benefit of being a little more performant over the lookup overhead of the dynamic call (can't find a reference for that statement, so I'll just float it out there).</p> <p>I suppose that doesn't answer your question directly, but rather is an alternative solution to accomplish the same goal. I haven't actually used #4.0 features yet (even though I'm a huge fan of the dynamic typing available in Ruby). It certainly not as clean/readable as the dynamic solution, but if you don't want to throw an exception it may be the way to go.</p> <p>EDIT: as @arbiter points out, "This is valid only for native .net dynamic objects. This will not work for example for IDispatch."</p>
    singulars
    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