Guard Class
Represents an argument checker. Exposes members used to validate method parameters.
Namespace: DevExpress.ExpressApp.Utils
Assembly: DevExpress.ExpressApp.v21.2.dll
Declaration
Remarks
The main purpose of the Guard class is to validate parameters passed into a method. The class “guards” methods from passing invalid parameters into them. Methods exposed by the Guard class are designed to throw exceptions if a parameter being checked does not pass validation.
Consider the following sample method:
public void MyMethod(object myObject, string message) {
if(myObject == null) {
throw new ArgumentNullException();
}
if(myObject.GetType() != typeof(MyType)) {
throw new ArgumentException();
}
else {
//...custom logic here
if(!string.IsNullOrEmpty(message)) {
//...custom logic here
}
}
}
Having argument checks throughout the body of the method clutters the code and makes it less readable. Moreover, checking arguments in such a manner is not a good way of declaring business logic. The following code snippet illustrates the same method rewritten using the Guard class:
public void MyMethod(object myObject, string message) {
Guard.ArgumentNotNull(myObject, nameof(myObject));
Guard.ArgumentNotNull(message, nameof(message));
Guard.TypeArgumentIs(typeof(MyType), myObject.GetType(), nameof(myObject));
//...custom logic here
}
As you can see, after the rewrite, the code became shorter and more readable. Also, by using the Guard class in such a manner we express and enforce a data contract. Combined with self-describing names of the Guard class’ methods, this makes the sample code rather self-documenting.
The following table lists the methods exposed by the Guard class:
Method | Description |
---|---|
Guard.ArgumentNotNull | Ensures that a specific argument is not a null reference. |
Guard.ArgumentNotNullOrEmpty | Ensures that a specific string argument is not a null reference and is not an empty string. |
Guard.CheckObjectFromObjectSpace | Ensures that a specific object belongs to a particular Object Space. |
Guard.CreateArgumentOutOfRangeException | Initializes a new ArgumentOutOfRangeException class with the specified argument name and value. |
Guard.NotDisposed | Ensures that a specific object has not been disposed. |
Guard.TypeArgumentIs | Ensures that an argument has a specific type. |
Related GitHub Examples
The following code snippets (auto-collected from DevExpress Examples) contain references to the Guard class.
Note
The algorithm used to collect these code examples remains a work in progress. Accordingly, the links and snippets below may produce inaccurate results. If you encounter an issue with code examples below, please use the feedback form on this page to report the issue.