Guard Class
Represents an argument checker. Exposes members used to validate method parameters.
Namespace: DevExpress.ExpressApp.Utils
Assembly: DevExpress.ExpressApp.v24.2.dll
NuGet Package: DevExpress.ExpressApp
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. |