Tuesday, 13 March 2018

043 C# Generics

Generic feature of. Net Framework.
It was added  in the version of 2.0. Generic allow  us delay declaration of the data type . User defined class , structure can be written and can be used as generic type during passing and initialization.

                             During compilation, compiler know how to handle the newly generated type. Generic is type safe  and  optimize code reuse.

Some points about generic
  • You can create class, structure, interface, method, delegates define by the user, considered a kind of  type.
  •  Generic comes under the namespace System.Collections.Generic
  •  Generic are type safe, no need to convert from object to actual type.
  •  Generic use the syntax , <T> is generic type. 
  • Genetic reduce overhead of explicit and implicit conversion, because during initialization , you are telling what type of data , will be hold in the collection. 

Here is the example of how a generic type is declared.

using System;
using System.Threading;
using System.Collections.Generic;

class Student<T1, T2>
{
     //Generic Type Variable Declaration
      private T1 mAge;

      //Generic Type Method
      public void GetFees(T1 value)
       {
        //State ment
      }

      // Return Generic Type
      public T2 genericMethod(T2 mAddress)
      {
         T2 obj;
         obj=mAddress;
        return obj;
       }

       //Generic Type Property
       public T1 StudentProperty
      {
          get
               {
               return mAge;
             }
         set
            {
              mAge = value; 
           }
     }
}

Initialize Constructor :
Generic type can be use to initialize a constructor. We can pass that Generic type to the constructor of a class,  depending upon the declaration. Here is a example.

using System;
using System.Threading;
using System.Collections.Generic;

class Student<T1, T2>
    {
          T1 Obj1;
          T2 Obj2;

               //Constructor Initialisation
                public Student(T1 a, T2 b)
                {
                  Obj1 = a;
                 Obj2 = b;
         }

              public void ShowData()
               {
                  Console.WriteLine("Obj1 :" + Obj1.ToString());
                  Console.WriteLine("Obj2 :" + Obj2.ToString());
              }
}

class School
{
         static void Main(string[] args)
        {
 
       //Example 1
           Student<string, string> myObj1;
           myObj1 = new Student<string, string>( "Hellow", " World");
           myObj1.ShowData();

         //Example 2
          Student<int, int> myObj2;
          myObj2 = new Student<int, int>(111,22);
          myObj2.ShowData();
 
    Console.ReadKey();
     }
}


Generic Method : A Method can also be Generic, we can pass generic type as a value type or reference type depending upon the declaration, the parameter can be single or multiple parameter. Generic support both.

using System;
using System.Threading;
using System.Collections.Generic;

class Student<T1, T2>
     {
         T1 Obj1;
        T2 Obj2;

          //Generic Type Methos
          public void MethodReturnGeneric<T1>(T1 a, T2 b)
         {
           T1 retu;
           retu = a;
           }

          //Generic Type Parameter , Pass By value
           public void Parameter_PassBy_Value(T1 a,T2 b)
           {
            Obj1 = a;
            Obj2 = b;
           Console.WriteLine("Obj1 :" + Obj1.ToString());
           Console.WriteLine("Obj2 :" + Obj2.ToString());
       }

          //Generic Type Parameter , Pass By Reference
         public void Parameter_PassBy_Reference(ref T1 a, ref T2 b)
         {
          Obj1 = a;
          Obj2 = b;
         Console.WriteLine("Obj1 :" + Obj1.ToString());
         Console.WriteLine("Obj2 :" + Obj2.ToString());
       }

}

class School
{
  static void Main(string[] args)
  {
     //Example 1
      Student<string, string> myObj1=new Student<string, string>();
     myObj1.Parameter_PassBy_Value("Hello", "World");
   //Example 2
     string str1 = "C#";
     string str2 = "Programming";
     myObj1.Parameter_PassBy_Reference(ref str1, ref str2);
    Console.ReadKey();
    }
}



Generic delegate : in the previous chapter we have seen, delegates are of three type
  • Single cast 
  • Multicast 
  • Generic. 
Generic type of delegate used Generic type , while raising event. Here is the example of generic type delegates.

class School
{
        public delegate T1 StudentCall(T1 a, T2 b);

        static void Main(string[] args)
        {
         
             StudentCall<int, int> gdInt = new StudentCall<int, int>(Example1);

         }

         public static int Example1(int a, int b)
         {
          return (a + b);
         }

        public static string Example2(string a, string b)
        {
         return (a + b);
        }

        public static int Example3(int a, int b)
        {
         return (a * b);
        }

       public static string Example3(string a, string b)
      {
        return (a + b);
       }

      public static string Example4(string a, int b)
      {
       return (b.ToString());
      }

}

Call The deligate:

School.StudentCall<int, int> obj = School.Example1;
Response.Write(School.Example1(5, 6));
//Output:11
Console.WriteLine(School.Example2("Hellow ", "World").ToString());
//Output:Hellow World




Generic interface : an interface can be declared using Generic type. Here is the example of interface using Generic type.

using System;
using System.Threading;
using System.Collections.Generic;
public interface IStudent1<T> : ICollection<T>
{
}
public interface IStudent2<T> : IEnumerable<T>
{
}
public interface IStudent3<T> : IList<T>
{
}
public interface IStudent4<T> : ICollection<T>
{
}

Example 1 

public interface Student<T> : IEnumerable<T>
{
         int Count { get; }
         bool Contains(T a);
         void CopyTo(T[] array, int ArrayIndex);
         bool IsReadOnly { get; }

        void Add(T a);
        void Clear();
        bool Remove(T a);
}

Example 2  
public interface Student<T> : IList<T>
{
           int Count { get; }
           bool Contains(T a);
           void CopyTo(T[] array, int ArrayIndex);
           bool IsReadOnly { get; }

           void Add(T a);
           void Clear();
           bool Remove(T a);
}

Example 3
   
public interface Student<T> : ICollection<T>
{
          int Count { get; }
          bool Contains(T a);
          void CopyTo(T[] array, int ArrayIndex);
          bool IsReadOnly { get; }

         void Add(T a);
         void Clear();
        bool Remove(T a);
}

042 C# Enum

Enum
enum is an keyword to inform compiler that it is an enumeration. Enumeration consist a set of values  related name constant , it is called enumeration list.The value should be distinct. Enumeration is declared generally under a namespace, but it can be declared under structure and class also. It is a value type object and do not support inheritance. By default for the set of value , enumeration value start from zero  if not specified. Enumeration value can be integer, byte, float , double.Below is the
enumeration with default enumeration value.

Example 1

using System;
namespace student
{
               public class Student
                {
                        enum DayofWeek
                         {
                              Sunday, Monday, Tuesday, Wednesday, Thrusdad, Friday, Saturday
                          };
                          static void Main()
                          {
                             int i = (int)DayofWeek.Tuesday;
                             Console.WriteLine("Value of i is " + i.ToString());
                            Console.ReadKey();
                          }


}
Output :
Value of i is 2

Example 2
Below is the example with first enumeration value 12


using System;
namespace student
{
             public class Student
             {
                    enum DayofWeek
                    {
                             Sunday=12, Monday, Tuesday, Wednesday, Thrusdad, Friday, Saturday
                   };

               static void Main()
              {
               int i = (int)DayofWeek.Tuesday;
               Console.WriteLine("Value of i is " + i.ToString());
               Console.ReadKey();
             }
        }
}


044 C# Anonymous Method

Anonymous Method 

Anonymous means which has no name or unknown name.. Net Framework in C# platform allow us to write method who has no name. Anonymous method has no name and no corresponding declaration no parameter passing no and no code block. Delegate is declared and pass code block to the delegate. Below is the example of a Anonymous method.

Example 1
 
using System;
public class Program
{
          public delegate void DemoAnonymous(int a,int b);
          public static void Main()
              {
                             DemoAnonymous obj = delegate (int x,int y)
                              {
                                  int c = x + y;
                                  Console.WriteLine("Thre Result is : {0}", c.ToString());
                               };
                             obj(100,200);
                             Console.ReadKey();
              }
}

Output :
 Thre Result is : 300

Advantage of anonymous method is 
  • Reduce code overhead. 
  • No need of separate area for method declaration. 
  • Simplified code for implementation. 

Here is some point about Anonymous Method 
  • Variable can be declared in Anonymous Method. 
  • Parameter can be passed to Anonymous Method from delegates. 
  • Anonymous Method can access variables outer scope. 
  • Anonymous Method cannot access ref or out parameter of the out of scope. 
  • Anonymous Method , if encounter jump , go , break statement to outer scope it will cause error. 
  • Anonymous Method can be worked with event Handler. 
  • Anonymous method cannot handle unsafe code. 

 Example 2

 Below is the example that Anonymous Method can access variables outer scope.
 
using System;
public class Program
          {
                      public delegate void DemoAnonymous(int a,int b);
                      public static int d = 200;

                      public static void Main()
                       {
                                   DemoAnonymous obj = delegate (int x,int y)
                                     {
                                        int c = x + y+d;
                                        Console.WriteLine("Thre Result is : {0}", c.ToString());
                                      };
                                     obj(100,200);
                                    Console.ReadKey();
                        }
        }

 Output :
 Thre Result is : 500



 Example 3

 Below is the example that Anonymous Method can be work with event handler.
------------------------------------------aspx Page------------------------------------------------------------------
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
         <title></title>
</head>
<body>
            <form id="form1" runat="server">
             <asp:Button ID="Button1" runat="server" Text="Button" />
             </form>
</body>
</html>
 -----------------------------------C# Code------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
              protected void Page_Load(object sender, EventArgs e)
             {
                    Button1.Click += delegate
                    {
                             string script = "";
                             System.Type obj = this.GetType();
                             ClientScript.RegisterStartupScript(obj, "mySite", script);
                     };
            }
}

Output :

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...