Contract Prerequisites in an Empty Body Constructor

Good morning! I am writing a class for drawing histograms, and for the convenience of users, I decided to add several convenience constructors.

However, as soon as I recently switched to a .NET contract with DevLabs, I want to fully use the preconditions to protect against my (or someone's) stupidity.

public HistoGrapher(IList<string> points, IList<T> values) : this(points.Select((point, pointIndex) => new KeyValuePair<string, T>(point, values[pointIndex]))) { Contract.Requires<ArgumentNullException>(points != null, "points"); Contract.Requires<ArgumentNullException>(values != null, "values"); Contract.Requires<ArgumentException>(points.Count == values.Count, "The lengths of the lists should be equal."); } public HistoGrapher(IEnumerable<KeyValuePair<string, T>> pointValuePairs) { // useful code goes here } 

Something bothers me. I do not want the first constructor to ever name the second if the contract was broken; however, it is assumed that a call to this(...) will be performed before the body of the first constructor is executed.

Will this code work the way I want? I have not tried it yet. And if not, is there any way to solve this problem?

+8
constructor c # code-contracts
source share
1 answer

And if not, is there any way to solve this problem?

Since the constructor body only executes after calling another constructor, I don't think your current approach might work. I would recommend decomposing the general code into a separate method, i.e. Init() , which you can then call from both constructors to save your DRY code and solve your problem:

 public class HistoGrapher { public HistoGrapher(IList<string> points, IList<T> values) { Contract.Requires<ArgumentNullException>(points != null, "points"); Contract.Requires<ArgumentNullException>(values != null, "values"); Contract.Requires<ArgumentException>(points.Count == values.Count, "The lengths of the lists should be equal."); var pointValuePairs = points.Select((point, pointIndex) => new KeyValuePair<string, T>(point, values[pointIndex])) Init(pointValuePairs); } public HistoGrapher(IEnumerable<KeyValuePair<string, T>> pointValuePairs) { Init(pointValuePairs); } private void Init(IEnumerable<KeyValuePair<string, T>> pointValuePairs) { // useful code goes here } } 
+5
source share

All Articles