Today when i want to verify an object is instantiated correctly with an injected argument, I do something like this:
public class SomeObject
{
private object _someArgument;
public SomeObject(object someArgument)
{
if (someArgument == null)
{
throw new ArgumentNullException("someArgument");
}
this._someArgument = someArgument;
}
}
But I was wandering if I can catch such issues at compile time to avoid errors in run time.
Eg
// Get a compilation error since null was passed
var someInstance = new SomeObject(null);
Is it possible to do?
You can use Code Contracts . It does not produce compile time errors. However it performs static checking on your code and gives warnings if it detects code like var someInstance = new SomeObject(null);
You can use it like this:
public SomeObject(object someArgument)
{
Contract.Requires(someArgument != null);
this._someArgument = someArgument;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.