C # Extension Classes

Source: Internet
Author: User

C # provides a very practical way to provide energy, extension methods (Extension method)

The extension method is to extend an existing type by an additional static method. By extending the method, you can do the related extensions you want to do with the existing types. Method: Defines a static class, the extension method is also a static method, and the first parameter of the extension method is the type to be extended, a This keyword must be attached.

examples are as follows:

Extension classes:

     Public Static classExtend { Public Static BOOLIsNullOrEmpty ( This Objecti) {if(i = =NULL)return true; if(I.gettype () = =typeof(string))            {                stringtemp = (string) I; returntemp.            IsNullOrEmpty (); }            Else return false; }         Public StaticGuid Toguid ( This stringi) {Guid id; if(! Guid.tryparse (I, outid)) {Throw NewException (i +"can not is converted to Guid"); }            returnID; }    }

Extension method Invocation:

 public  class   Testextend { public  void   Test () { string  i =  " this a World for me   "             try   {GUID GUID = I.toguid (); Console.Write (GUID.            ToString ());                 catch   (Exception ex) { Console.WriteLine (ex.            Message); }        }    }

C # Extension Classes

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.