Saturday, March 1, 2014

Structure & Extension Method

Structures

This concept is not new in C#; it is taken from C language. In  C  language‘s  structures,  you  can  write  only  some  member  variables,  called  as  "data members"  / "fields".  But  in  C#‘s  structures,  you  can  write  fields  along  with  some methods also. So,  In  C#,  structures  are  almost  all  similar  to  the classes,  but  having  some  differences with the classes.
structure
Implementation:
  • Define structure

         struct structurename
            {
              //fields
              //methods
            }

  • Create instance for structure

          structurename instancename = new structurename();


structure program

Download above Code for Demo on Structure : Downloads Links

 Extension Methods

This is concept is meant for extending the methods of a class
There are two ways to extend a class:
  • Inheritance
  • Extension Methods
  1. As you know already in "inheritance", you can extend the features of a class by defining derived class.
  2. But  in  this  "inheritance"  feature,  you  are  creating  two  classes  (base  class  and  derived class).
  3. But,  if  you  want  to  add  a  method  to  an  existing  class,  that  is  accessible  with  the objects  of  the  same  class,  it  is  not  possible  in  "inheritance".  But  it  is  possible  using "Extension Methods".
  4. Conclusion:  This  feature  allows  you  to  add  one  or  more  new  methods  to  the  same class, without changing the definition of that particular class.
  5. This is more useful, when you want to add more methods to a pre-defined class.
Implementation:
  • When you want to implement this concept practically, simply take a new static class first.
  • In this static class, write a static method, with the required name.
  • In that method, the first argument should be like this:

                     this  classname  argumentname

  • Here,  in  place  of  "classname",  specify  the  class  name,  for  which  you  want  to  write  the extension method.
  • Then the "argument name" acts as "this" pointer in the code.

Note:  Even  though  it  is  defined  as  a  "static  method"  it  is  accessible  as  a  non-static method from the object of the source class.

Syntax:

  public static return_type method_name(this class_name arg, <other args if any>)
      {
       //some code
      }

Limitation: You can‘t add a static method for an existing class.
Extension Method

Download above code for Demo of Extension Method : Download Links

No comments:

Post a Comment

Flag Counter