Thursday, September 14, 2017

Static Keyword

When we declare a class as Static then all the elements in the class will be static.If the class is Static then Most of the oops features won't be applied on this class. Like No inheritance, No polymorphism,No Interface, No Abstract etc.
Even the object of this class will be created only once in memory, therefore its constructor will be suitable for caching in memory data.
Mostly Static class is Utility class which doesn't have anything do do with real world object.

Wednesday, September 13, 2017

Copy Constructor

A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance. 

using System;
namespace ConsoleApplication3
{
class CopyConstructor
{
public string p1, p2;
public CopyConstructor(string x, string y)
{
p1 = x;
p2 = y;
}
public CopyConstructor(CopyConstructor obj)     // Copy Constructor
{
p1 = obj.p1;
p2 = obj.p2;
}
}
class Program
{
static void Main(string[] args)
{
CopyConstructor obj = new CopyConstructor("Hello""Friend");  /
CopyConstructor  obj1=new CopyConstructor (obj); // Here obj details will copied to obj1
Console.WriteLine(obj1.p1 +" to " + obj1.p2);
Console.ReadLine();
}
}
}

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.

Static Constructor in C#

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. public class MyStaticClass
  2. {
  3. static int count;
  4. static MyStaticClass()
  5. {
  6. count = 0;
  7. Console.WriteLine("Static class is initialized");
  8. }
  9. It can only access the static member(s) of the class.
  10. There should be no parameter(s) in static constructor, therefore static constructor overloading not possible.
    Reason: Since, It is going to be called by CLR, nobody can pass the parameter to it.
  11. There should be no access modifier to it.
  12. 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
    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. }

    12. 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.

Extension Method in C#

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. At compile time an extension method call is translated into an ordinary static method call.
We want to extend the string object with a new function WordCount
  1. //defining extension method
  2. public static class MyExtensions
  3. {
  4. public static int WordCount(this String str)
  5. {
  6. return str.Split(new char[] { ' ' }).Length;
  7. }
  8. }
  9.  
  10. class Program
  11. {
  12. public static void Main()
  13. {
  14. string s = "I am Extension Method";
  15. int i = s.WordCount();
  16.  
  17. Console.WriteLine(i);
  18. }
  19. }


Tuesday, September 12, 2017

Lambda Expression

The concept of lamda expression was introduced in C# 3.0. Basically, Lamda expression is a more concise syntax of anonymous method. It is just a new way to write anonymous methods. At compile time all the lamda expressions are converted into anonymous methods according to lamda expression conversion rules.The left side of the lamda operator "=>" represents the arguments to the method and the right side is the method body.
Syntax:
(parameters) => expression-or-statement-block 
Example:
(x,y) => { return x * y; }; // Statement Lambda
(x,y) => x * y;// Expression Lambda without return statement or curly braces

Features of lamda expression
Lambda expressions themselves do not have type. In fact, there is no concept of a lambda expression in the CLR.
 // ERROR: Operator '.' cannot be applied to
// operand of type 'lambda expression'
Type type = ((int x) => x).ToString(); 
A lambda expression cannot be assigned to an implicitly typed local variable since the lambda expressions do not have type.
 // ERROR: Cannot assign lambda expression to an
// implicitly typed local variable
var thing = (x => x); 
Jump statements (break, goto, continue) are not allowed within anonymous method/lambda expression. Similarly, you cannot jump into the lambda expression/ anonymous method from outside.
Variables defined within a lambda expression are accessible only within the scope of the lambda expression body.
Lambda expressions are used generally with the Func and Action delegates. our earlier expression can be written as follows:
 Func sqr = x => x * x; 

Anonymous method with Lambda and delegate
class Program
{
 //delegate for representing anonymous method
 delegate int del(int x, int y);

 static void Main(string[] args)
 {
 //anonymous method using expression lamda
 del d1 = (x, y) => x * y; 
 // or (int x, int y) => x * y;

 //anonymous method using statement lamda
 del d2 = (x, y) => { return x * y; }; 
 // or (int x, int y) => { return x * y; };

 //anonymous method using delegate keyword
 del d3 = delegate(int x, int y) { return x * y; };

 int z1 = d1(2, 3);
 int z2 = d2(3, 3);
 int z3 = d3(4, 3);

 Console.WriteLine(z1);
 Console.WriteLine(z2);
 Console.WriteLine(z3);
 }
}
//output:
6
9
12

Lamda expression as an Event Handler
 <form id="form1" runat="server">
 <div align="center">
<h2>Anonymous Method Example</h2>
 <br />
 <asp:Label ID="lblmsg" runat="server" ForeColor="Green" Font-Bold="true"></asp:Label>
 <br /><br />
 <asp:Button ID="btnReset" runat="server" Text="Reset" />  
 <asp:Button ID="btnSubmit" runat="server" Text="Submit" />  
 <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
 </div>
 </form> 


 protected void Page_Load(object sender, EventArgs e)
 {
 // Click Event handler using Regular method
 btnReset.Click += ClickEvent;
 // Click Event handler using Anonymous method
 btnSubmit.Click += delegate { lblmsg.Text="Submit Button clicked using Anonymous method"; }; 
// Click Event handler using Lamda expression 
btnCancel.Click += (senderobj, eventobj) => { lblmsg.Text = "Cancel Button clicked using Lamda expression"; };
 }
 protected void ClickEvent(object sender, EventArgs e)
 {
 lblmsg.Text="Reset Button clicked using Regular method";
 } 
  

x

Anonymous Method

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.

  1. class Program
  2. {
  3. //delegate for representing anonymous method
  4. delegate int del(int x, int y);
  5. static void Main(string[] args)
  6. {
  7. //anonymous method using delegate keyword
  8. del d1 = delegate(int x, int y) { return x * y; };
  9. int z1 = d1(2, 3);
  10. Console.WriteLine(z1);
  11. }
  12. }
  13. //output:
  14. 6
  15. Anonymous Method as an Event Handler
    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. }
    12. Key points about 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.