Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'll post this as a different answer, because it is characteristically different than Code Contracts.</p> <p>One approach you can use to have declarative validation is to use a dictionary or hash table as the property store, and share a utility method to perform validation.</p> <p>For example:</p> <pre><code>// Example attribute class for MaxStringLength public class MaxStringLengthAttribute : Attribute { public int MaxLength { get; set; } public MaxStringLengthAttribute(int length) { this.MaxLength = length; } } // Class using the dictionary store and shared validation routine. public class MyDataClass { private Hashtable properties = new Hashtable(); public string CompanyName { get { return GetValue&lt;string&gt;("CompanyName"); } [MaxStringLength(50)] set { SetValue&lt;string&gt;("CompanyName", value); } } public TResult GetValue&lt;TResult&gt;(string key) { return (TResult)(properties[key] ?? default(TResult)); } public void SetValue&lt;TValue&gt;(string key, TValue value) { // Example retrieving attribute: var attributes = new StackTrace() .GetFrame(1) .GetMethod() .GetCustomAttributes(typeof(MaxStringLengthAttribute), true); // With the attribute in hand, perform validation here... properties[key] = value; } } </code></pre> <p>You can get at the calling property using reflection by working up your stack trace as <a href="http://www.csharp-examples.net/reflection-calling-method-name/" rel="nofollow noreferrer">demonstrated here</a>. Reflect the property attributes, run your validation, and <em>voila!</em> One-liner getter/setters that share a common validation routine.</p> <p>On an aside, this pattern is also convenient because you can design a class to use alternative dictionary-like property stores, such as ViewState or Session <em>(in ASP.NET)</em>, by updating only <code>GetValue</code> and <code>SetValue</code>.</p> <p>One additional note is, should you use this approach, you might consider refactoring validation logic into a validation utility class for shared use among all your types. That should help prevent your data class from getting too bulky in the <code>SetValue</code> method.</p>
 

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