Wednesday, 14 August 2013

C# Extension method

An extension method is a static method of a static class that can be invoked using the instance method syntax. Extension methods are used to add new behaviors to an existing type without altering. In extension method "this" keyword is used with the first parameter and the type of the first parameter will be the type that is extended by extension method.
Conceptually, extension methods provides as an implementation of the decorator structural pattern.
  1. public static class ExtensionClass {
  2. public static bool IsCapitalized (this string s)
  3. { if (string.IsNullOrEmpty(s))
  4. return false;
  5. else
  6. return char.IsUpper (s[0]); }
  7. }
  8. class Program {
  9. static void Main(string[] args)
  10. { bool flag;
  11. string str="Dotnet-tricks"
  12. if(str.IsCapitalized()) //invoking the extension method
  13. Console.WriteLine ("\n The given string is capitalized");
  14. else
  15. Console.WriteLine ("\n The given string is not capitalized"); }
  16. }
At compile time an extension method call is translated into an ordinary static method call. The translation of above static method will as follows:
  1. ExtensionClass.IsCapitalized (str)

Extension Methods Chaining

Like as instance methods, extension methods also have chaining capability.
  1. public static class ExtensionClass
  2. {
  3. public static string Pluralize (this string s) {...}
  4. public static string Capitalize (this string s) {...}
  5. }
  6. //we can do chainig of above methods like as
  7. string x = "Products".Pluralize().Capitalize();

Ambiguity, resolution and precedence of extension method

To use an extension method, it should be in same scope of class.If two extension methods have the same signature,the more specific method takes precedence.
  1. static class StringExtension
  2. { // first method
  3. public static bool IsCapitalized (this string s) {...}
  4. }
  5. static class ObjectExtension
  6. {
  7. // second method
  8. public static bool IsCapitalized (this object s) {...}
  9. }
  10. // code here
  11. // first method is called
  12. bool flag1 = "Dotnet-Tricks".IsCapitalized();
  13. // second method is called
  14. bool test2 = (ObjectHelper.IsCapitalized ("Dotnet-Tricks"));

Key points about extension methods

  1. An extension method is defined as static method but it is called like as instance method.
  2. An extension method first parameter specifies the type of the extended object, and it is preceded by the "this" keyword.
  3. An extension method having the same name and signature like as an instance method will never be called since it has low priority than instance method.
  4. An extension method couldn't override the existing instance methods.
  5. An extension method cannot be used with fields, properties or events.
  6. The compiler doesn't cause an error if two extension methods with same name and signature are defined in two different namespaces and these namespaces are included in same class file using directives. Compiler will cause an error if you will try to call one of them extension method.

C Sharp Anonymous Method

The concept of anonymous method was introduced in C# 2.0. An anonymous method is inline unnamed method in the code. It is created using the delegate keyword and doesn’t required name and return type. Hence we can say, an anonymous method has only body without name, optional parameters and return type. An anonymous method behaves like a regular method and allows us to write inline code in place of explicitly named methods.

Features of anonymous method

  1. A variable, declared outside the anonymous method can be accessed inside the anonymous method.
  2. A variable, declared inside the anonymous method can’t be accessed outside the anonymous method.
  3. We use anonymous method in event handling.
  4. An anonymous method, declared without parenthesis can be assigned to a delegate with any signature.
  5. Unsafe code can’t be accessed within an anonymous method.
  6. An anonymous method can’t access the ref or out parameters of an outer scope.

Assign an Anonymous Method to a Delegate

  1. delegate int MathOp(int a, int b);
  2. public static void Main() { //statements
  3. MathOp op = delegate(int a, int b) { return a + b; };
  4. int result = MathOp(13, 14);
  5. //statements
  6. }

Anonymous Method as an Event Handler

  1. <form id="form1" runat="server">
  2. <div align="center">
  3. <h2>Anonymous Method Example</h2>
  4. <br />
  5. <asp:Label ID="lblmsg" runat="server" ForeColor="Green" Font-Bold="true"></asp:Label>
  6. <br /><br />
  7. <asp:Button ID="btnSubmit" runat="server" Text="Submit" />  
  8. <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
  9. </div>
  10. </form>

  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. // Click Event handler using Regular method
  4. btnCancel.Click += new EventHandler(ClickEvent);
  5. // Click Event handler using Anonymous method
  6. btnSubmit.Click += delegate { lblmsg.Text="Submit Button clicked using Anonymous method"; };
  7. }
  8. protected void ClickEvent(object sender, EventArgs e)
  9. {
  10. lblmsg.Text="Cancel Button clicked using Regular method";
  11. }
 

Constructor

In C#, Constructors are the special types of methods of a class which get executed when it's object is created. Constructors are responsible for object initialization and memory allocation of its class. There is always at least one constructor in every class. If you don't write a constructor in class, C# compiler will automatically provide one constructor for that class, called default(parameter less) constructor.

Types of Constructor

Generally, constructors are of three types. But C# doesn't support copy constructor.
  1. Default Constructor(Non-Parametrized constructor)
  2. Parametrized Constructor
  3. Copy Constructor

Default Constructor with example

  1. using System;
  2. Class example1 {
  3. int roll; float marks;
  4. public example1() //constructor
  5. {
  6. roll=0;
  7. marks=0.0;
  8. }
  9. // other members
  10. }
The above mentioned constructor example1() doesn't take any argument therefore it is an example of default/non-parameterized constructor. With this type of constructor, the object will be created as follows :
  1. example1 obj1 = new example1 ();

Parameterized Constructor with example

  1. Class example2
  2. {
  3. int roll;
  4. float marks;
  5. public example2(int a, float b)//constructor
  6. {
  7. roll = a;
  8. marks = b;
  9. }
  10. //other members
  11. }
The above defined constructor takes two arguments one int and other float to initialize instance members roll and marks for the newly created object and therefore it is called parameterized constructor. With this type of constructor, the object will be created as follows :
  1. example2 obj = new example2( 5 , 33.05F);

Constructor Overloading

In C# it possible to overload the constructors, it means we can have more than one constructor with different parameters
  1. using System;
  2. public Class OverloadConst
  3. {
  4. public OverloadConst()
  5. {
  6. //Default constructor
  7. }
  8. public OverloadConst(int age)
  9. {
  10. //Single parameter constructor
  11. }
  12. public OverloadConst(int age, string name)
  13. {
  14. //two parameter constructor
  15. }
  16. }

Now, following are the ways through which we can instantiate the object

  1. OverloadConst obj=new OverloadConst() ; //Default constructor will get called
  2. OverloadConst obj=new OverloadConst(33) ; //Single parameter constructor will get called
  3. OverloadConst obj=new OverloadConst(35,"asif") ; //Two parameters constructor will get called
In above example you have seen that constructor overloading is completely governed by the rule of overloading , i.e, overloading must need two or more method to be different in terms of method signature.

Now, one question here for you , can we have two constructor like this ?

  1. using System;
  2. public Class question {
  3. static question()
  4. {
  5. // initialize static member only.
  6. }
  7. public question()
  8. {
  9. //codes for the first derive class constructor.
  10. }
  11. }
The answer to this question is on hold unto the discussion over static constructor.
Many a place you might have been read that a constructor can't be declared as static, this is not true for C# there can be a static constructor in C# .However, it is true for earlier language like C++ .

Static Constructors

Static constructor is a special constructor that gets called before the first object of the class is created. It is used to initialize any static data, or to perform a particular action that needs performed once only.
The time of execution of static constructor is not known but it is definitely before the first object creation - may be at the time of loading assembly.
  1. //Example1
  2. using System;
  3. public Class abc
  4. {
  5. static abc()
  6. {
  7. // initialize static members only.
  8. }
  9. // other methods here.
  10. }
  11. // Example2
  12. using System;
  13. public class MyStaticClass
  14. {
  15. static int count;
  16. static MyStaticClass()
  17. {
  18. count = 0;
  19. Console.WriteLine("Static class is initialized");
  20. }
  21. public static void MyMethod(string name)
  22. {
  23. Console.WriteLine("Static class is initialized " + name);
  24. }
  25. }
  26. MyStaticClass.MyMethod("John") ; //method call
  27. //constructor will be called automatically
  28. Output:
  29. Static class is initialized Hello John

Key points about static constructor

  1. It can only access the static member(s) of the class.
  2. Reason : Non static member is specific to the object instance. If static constructor are allowed to work on non static members it will reflect the changes in all the object instance, which is impractical.
  3. There should be no parameter(s) in static constructor.
    Reason: Since, It is going to be called by CLR, nobody can pass the parameter to it.
  4. Only one static constructor is allowed.
    Reason: Overloading needs the two methods to be different in terms of method/constructor definition which is not possible in static constructor.
  5. There should be no access modifier to it.
    Reason: Again the reason is same call to static constructor is made by CLR and not by the object, no need to have access modifier to it
Now, the answer of the question I asked earlier for the following class definition that - can we have two constructors like this?
  1. using System;
  2. public Class question {
  3. static question()
  4. {
  5. //initialize static member only.
  6. }
  7. public question()
  8. {
  9. // codes for the first derive class constructor.
  10. }
  11. }
Ans : Yes, this is perfectly valid even if it doesn't match with the rule of overloading concept. The only reason of being it valid is that the time of execution of the two constructors are different, (i) static question() at the time of loading the assembly and (ii) public question() at the time of creating object.

Private Constructor

A private constructor is a special instance constructor used in class that contain static member only. If a class have one or more private constructor and no public constructor then other classes (except nested classes ) are not allowed to create instance of this class. Means, we can neither create the object of the class nor it can be inherit by other class.
The public constructor can access the private constructors from within class through constructor chaining.
  1. using System;
  2. public Class demo {
  3. private demo()
  4. {
  5. Console.WriteLine("This is no parameter private constructor");
  6. }
  7. public demo(int a):this()
  8. {
  9. Console.WriteLine("This is one parameter public constructor");
  10. }
  11. // other methods
  12. }
The object of the class can be created as :
  1. demo obj = new demo(10) ; //it will work fine.
But defining object like this won't work.
  1. demo obj = new demo() ; // error of inaccessibility will be occur.

Key points about private constructor

  1. one use of private construct is when we have only static member.
  2. It provide implementation of singleton class pattern
  3. Once we provide constructor (private/public/any) the compiler will not add the no parameter public constructor to any class.
  4. If we still want to make object of the class having private constructor. We can have a set of public constructor along with the private constructor.