Using extension methods to validate calls in C #

Source: Internet
Author: User

With the extension method technology provided by C # 3.0, you can add new methods to the compiled assembly type to cope with the new extension. In addition to the advantages of scalability, if you can reasonably combine generics with type inference, extension methods can effectively reduce the duplication of code and improve the reusability of programs. For example, this method implements the following:

public class Customerdal
{public
    ienumerable<customer> findcustomers (string rolename)
    {
        Return from the customer in context
            . Customer
               where customer. Rolename.equals (rolename)
               Select customer;
    }

When the result returned by the method is null, the NullReferenceException exception is thrown by using the following method:

Customer customer = new Customerdal (). Findcustomers (role.admin). A ();

We need to validate the return result, and if we return to NULL, we can throw a custom exception, or create an empty object, for example:

Public ienumerable<customer> findcustomers (string rolename)
{
    ienumerable<customer> customers = From the customer in context
            . Customer
            where customer. Rolename.equals (rolename)
            Select customer;
    if (customers = = null)
    {
        throw new MyException ("Cann ' t find the customers.");
    }
    return customers;
}

If there are many methods in the system that require validation of the return results, such validation logic will be flooded into the body of the method, which is not conducive to reuse, and can be a great hindrance to future modifications. Of course, we can introduce the null object pattern to replace the judgment logic for null values, but this way we still need to define different null object types for multiple types.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.