Some simple techniques but very useful in c #

Extension method.

C # 3.0 comes with a series of techniques such as: Lambda expressions, LINQ … and in which "Extension method" is one of the pretty good techniques was born with this update. Just looking at the name we have already guessed its meaning, it is an extension of all methods / objects, from the objects of the framework to the object we develop, it can be write expandable.

Advantages and disadvantages:

  1. Advantages
    _ Add methods / actions to an object that you don't need to inherit that object.
    _ Avoiding excessive redundancy and reusing code is very high.
  2. Defect
    _ Lower priority than official methods.
    _ If the object is expanded (the original object) has any changes to the structure or affects the rule of writing the extension method, then it is likely that your method will no longer be available.

A few points to note:

_ Extension method does not change the source code.

_ The extension method must be a static method, accompanied by the "static" keyword.

_ If you want to use extension classes, you must use its namespace.

_ Always included with the keyword "this".

_ If you use visual studio IDE, you are very aware of the extension method when calling it: it is a broken arrow image.



I'll take a specific example.


_ The above command block is expanding for Datetime 4 methods: First and last days of month, first and last days of the year. and the result will look like the image below.


_ As you can see, the two methods (with the nose shape) named FirstDayOfMonth and FirstDayOfYear have been added to the Datetime object, which was originally not available from Microsoft.

_ So you've completely got your own extension class, just close it to a DLL that we can use for any project.

_ You can refer to Microsoft's LINQ library, typically in the Queryable class, the entire method is written extensively for objects such as IQueryable, IEnumerable …

Conclusion: Through this sharing article, I hope you can apply good methods of using extension methods, a good code structure + with the use of reasonable extension method, make sure your code is maintained later. very advantageous.

ITZone via Viblo

Share the news now