Public · Protected · Private
Extension methods in c#
Type: Public  |  Created: 2012-08-07  |  Frozen: Yes
« Previous Public Blog Next Public Blog »
Comments
  • 1) Extension methods need to be defined at a top level namespace. 2) class name does not matter much 3) parameter has "this" with one argument see below ... namespace MyUtilities { public static class MyOwnMethods { public static int myExtFoo(this String str) { return str.Split(new char[] { ' ', '.', '?' }).Length; } public static int myExtFoo(this int myint) { return myint / 2; } } } // by arguments "this String str" "this int myint" ... I extended string methods and int methods. now the caller can call it as below ... using MyUtilities; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string h = "My name is janaganamana"; int y = h.myExtFoo(); y = y.myExtFoo(); MessageBox.Show (y.ToString()); } } } Notice the overloading too..

     

    more practical use @ http://www.janaganamana.net/onedefault.aspx?bid=1002

    2012-08-07 10:03
This blog is frozen. No new comments or edits allowed.