Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In addition to Ben's code I'd like to contribute the following code fragment:</p> <pre><code>Dictionary&lt;string,object&gt; PropertyCorrectValues = new Dictionary&lt;string,object&gt;(); PropertyCorrectValues["UserName"] = "Pete"; // propertyName PropertyCorrectValues["SomeClass.AccountData"] = "XYZ"; // className.propertyName public void CheckAndCorrectProperties(object obj) { if (obj == null) { return; } // find all properties for given object that need to be checked var checkableProps = from props in obj.GetType().GetProperties() from corr in PropertyCorrectValues where (corr.Key.Contains(".") == false &amp;&amp; props.Name == corr.Key) // propertyName || (corr.Key.Contains(".") == true &amp;&amp; corr.Key.StartsWith(props.DeclaringType.Name + ".") &amp;&amp; corr.Key.EndsWith("." + props.Name)) // className.propertyName select new { Property = props, Key = corr.Key }; foreach (var pInfo in checkableProps) { object propValue = pInfo.Property.GetValue(obj, null); object expectedValue = PropertyCorrectValues[pInfo.Key]; // checking for equal value if (((propValue == null) &amp;&amp; (expectedValue != null)) || (propValue.Equals(expectedValue) == false)) { // setting value pInfo.Property.SetValue(obj, expectedValue, null); } } } </code></pre> <p>When using this "automatic" value correction you might also consider:</p> <ul> <li>You cannot create a <code>PropertyInfo</code> object just by knowing the property name and independently of the declaring class; that's why I chose <code>string</code> for the key.</li> <li>When using the same property name in different classes then you might need to change the code that is doing the actual assignment because the type between the correct value and the property type might differ.</li> <li>Using the same property name in different classes will always perform the same check (see point above), so you might need a syntax for property names to restrict it to a specific class (simple dot notation, doesn't work for namespaces or inner classes, but might be extended to do so)</li> <li>If needed you can replace the "check" and "assign" part with separate method calls, but it might be done inside the code block as stated in my example code.</li> </ul>
    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. This table or related slice is empty.
    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