How to create a static method extension in .NET

Jump to: navigation, search

This example how to create a public method in .NET In the Extensions folder of your project, create a cs file named myExtensions.cs with the following content: namespace MyProjectName.Extensions { public static class MyExtensions { public static int Square(this int x) { return x * x; } } } Because we used the "this" keyword we have actually extended the class of integers to have the method Square. Now in another .cs file you can call Square. You will need to add the following using statement using MyProjectName.Extensions; and call the Square method from your integer variable... var x =3; var y = x.Square(); If you remove the "this" keyword from the method defintion, you could just call the method explictly... var y = MyExtentsions.Square(x);

See also

Use your Android as a Liftmaster garage door opener remote

Personal tools
Namespaces
Variants
Views
Actions
Navigation