I'm a fan of the "fail early" strategy and want to check that methods params have correct values for example. In Java I'd use something like Guava:
checkArgument(count > 0, "must be positive: %s", count);
Is there something similar for .NET?
I'm a fan of the "fail early" strategy and want to check that methods params have correct values for example. In Java I'd use something like Guava:
checkArgument(count > 0, "must be positive: %s", count);
Is there something similar for .NET?
What you want to do is Design By Contract.
You should use Code Contracts for defining contracts i.e. Preconditions, post-conditions and invariants for your types\methods in C#.
IMO the best and most comprehensive coverage of code-contracts is here.
Code contracts: http://msdn.microsoft.com/en-us/devlabs/dd491992
Code Contracts are still an add on/not part of the standard Visual Studio install, but they do allow you to express pre and post conditions and object invariants.
Different options are available for enforcing the contracts as compile-time or run-time checks (or both).
Take a look at CuttingEdge.Conditions. It allows you to write your preconditions in a fluent manner, as follows:
ICollection GetData(int? id, string xml, IEnumerable<int> col)
{
Condition.Requires(id, "id")
.IsNotNull()
.IsInRange(1, 999)
.IsNotEqualTo(128);
Condition.Requires(xml, "xml")
.StartsWith("<data>")
.EndsWith("</data>")
.Evaluate(xml.Contains("abc") || xml.Contains("cba"));
Condition.Requires(col, "col")
.IsNotNull()
.IsNotEmpty()
.Evaluate(c => c.Contains(id.Value) || c.Contains(0));
}
You need C# 3.0 or VB.NET 9.0 with .NET 2.0 or up for CuttingEdge.Conditions.
© 2022 - 2024 — McMap. All rights reserved.