How one can use guard clauses in C#

  • You should use guard clauses in your strategies to stop runtime exceptions by dealing with null reference exceptions.
  • You should use guard clauses to validate enter information and implement information integrity by solely processing legitimate inputs.
  • You should use guard clauses to outline preconditions in your strategies and properties, enhancing the readability and maintainability of your code.

We’ll study every of those points of guard clauses utilizing code examples within the sections that observe.

Use a guard clause to keep away from null reference exceptions in C#

Null reference exceptions are sometimes encountered in functions while you use an object reference that has not been initialized. On this part, we are going to study how we will use a guard clause to stop such exceptions from being thrown at runtime. The next code snippet reveals how one can verify if the parameter of a way is null and throw an ArgumentNullException, stopping a null reference exception from being thrown at runtime and permitting the strategy to finish gracefully.


public void CheckIfNull(object obj)
{
    if (obj is null)
    {
        throw new ArgumentNullException(nameof(obj), "Methodology parameter can't be null.");
    }
    //Different code
}

Use a guard clause to implement enter validation guidelines in C#

Enter validation lets you preserve information integrity by implementing validation guidelines and constraints in your utility. You may implement guard clauses in your utility’s supply code to permit solely legitimate information to be processed by your utility.

The next code instance reveals how you should use a guard clause in C# to stop invalid enter. Notice how an exception is thrown if the enter string is null or empty.


public void CheckIfNullOrEmpty(string str)
{
    if(!string.IsNullOrEmpty(str))
    {
        throw new ArgumentException("Invalid information: The string handed within the methodology argument can't be empty or null");
    }
    //Different code
}

Use a guard clause to boost code readability and maintainability in C#

Guard clauses enable you write maintainable and readable code by centralizing your utility’s validation guidelines. They supply a sublime technique to stop surprising habits in your utility’s code, making it constant, organized, and straightforward to keep up.

Allow us to perceive this with a code instance. Within the console utility undertaking we created earlier, create a brand new class named Creator and enter the next code.


class Creator
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Deal with { get; set; }
    public string E-mail { get; set; }
}

The next code snippet illustrates how one can reap the benefits of the constructor of the Creator class to validate enter.


 public Creator(string firstName, string lastName, string handle, string electronic mail)
 {
     if (string.IsNullOrEmpty(firstName))
     {
         throw new ArgumentException("First title can't be null or empty", nameof(firstName));
     }
     if (string.IsNullOrEmpty(lastName))
     {
         throw new ArgumentException("Final title can't be null or empty", nameof(lastName));
     }
     if (string.IsNullOrEmpty(handle))
     {
         throw new ArgumentException("Deal with can't be null or empty", nameof(handle));
     }
     if (string.IsNullOrEmpty(electronic mail))
     {
         throw new ArgumentException("E-mail can't be null or empty", nameof(electronic mail));
     }
 }

As you’ll be able to see, the previous code snippet is sort of verbose. We will make it way more concise and readable through the use of guard clauses. Notice that the next code can exchange all the if statements used within the constructor of the Creator class above.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles