Wednesday, December 24, 2014

Generics in c#

Overview:
  • Generic classes have type parameters.
  • It is type independent because we can use any type.
  • The letter T denotes a type.
  • Instance of T like it is a real type, but it is not.
  • It helps us to create strong type in compile time, code reuse and performance.
Example:
  •  Example 01 :
            public class GenericClass<T>
           {
                     T _value;
                     public GenericClass(T valueParam)
                    {
                             this._value = valueParam;
                     }
                     public void Write()
                    {
                             Console.WriteLine(this._value);
                     }
            }

            class Program
            {
                    static void Main(string[] args)
                    {
                             GenericClass<int> objOne = new GenericClass<int>(1);
                             objOne.Write();

                             GenericClass<string> objTwo = new GenericClass<string>("Saniul Naim");
                             objTwo.Write();

                            Console.ReadLine();
                    }
             }


            Output: 1
                           Saniul Naim  
  • Example 02 :

       public struct Point<T>
        {
            public T x;
            public T y;
        }
     class Program
        {
            static void Main(string[] args)
            {
                     Point<double> decimalOjbWithInstatiation=new Point<double>();
                     decimalOjbWithInstatiation.x = 3.3;
                     decimalOjbWithInstatiation.y = 2.1;
                     Console.WriteLine("x={0},y={1}", decimalOjbWithInstatiation.x,                                                            decimalOjbWithInstatiation.y);

                     Point<int> decimalOjbWithoutInstatiation;
                    decimalOjbWithoutInstatiation.x = 3;
                    decimalOjbWithoutInstatiation.y = 2;
                    Console.WriteLine("x={0},y={1}",decimalOjbWithoutInstatiation.x,                                                        decimalOjbWithoutInstatiation.y);

                   Console.ReadLine();
            }
        }

       Output: x=3.3,y=2.1
                      x=3,y=2
                            
        Note: Notice that first we instantiate Point class but second time is not. But both two is working well. So what's the different between two!!!???

                 Ans: In brief, here Struct is immutable so if we need to zero the memory we need   instantiate.
      
Multiple Generic Types:
  •   Example 01 :
         public class MultipleGenericClass<T, K>
             {
                    private T tValue;
                    private K kValue;

                    public MultipleGenericClass(T tParam, K kParam)
                   {
                                tValue = tParam;
                                kValue = kParam;
                    }

                    public void Write()
                   {
                               Console.WriteLine("{0}{1}", tValue, kValue);
                   }
             }

             class Program
             {
                             static void Main(string[] args)
                            {
                                    MultipleGenericClass<string, int> multipleGenericClassObj = new                                                              MultipleGenericClass<string, int>("My age is ", 25);
                                    multipleGenericClassObj.Write();

                                    Console.ReadLine();
                             }
             } 
            Output:  My age is 25 

Generic class Constrain:
  • Here type T is fixed such as struck, class etc. 
  • We can fixed type by 'where' condition such as 'where T : struck'.
 Example:
  •  Example 01 :
           // This generic class can be call who is inherit from IDisposable
           public class DisposableGenericClass<T> where T :IDisposable
          {
           }

          // This generic class can be call who is struct such as integer.
          public class StructGenericClass<T> where T : struct
         {
          }

         // This generic class can be call who is struct such as integer.
         public class ClassGenericClass<T> where T : class ,new()
        {
         }

         class Program
        {
                static void Main(string[] args)
               {
                      // We know DataTable implements from IDisposable
                      DisposableGenericClass<DataTable> disposableObj = new                                                                                                DisposableGenericClass<DataTable>();


                     //int,decimal is value type which is struct
                     StructGenericClass<decimal> structObj = new StructGenericClass<decimal>();


                    //Program is parameterless constructor
                     ClassGenericClass<Program> classObj = new ClassGenericClass<Program>();


                    Console.ReadLine();
        }
    }

  •  


Generic And Abstract Class:
  • Example 01 :
       public abstract class BaseCalculator<T>
          {
                      public abstract T Add(T arg1, T arg2);
                      public abstract T Subtract(T arg1, T arg2);
           }
           public class Calculator : BaseCalculator<int>
          {
                      public override int Add(int arg1, int arg2)
                     {
                               return arg1 + arg2;
                      }
                     public override int Subtract(int arg1, int arg2)
                    {
                               return arg1 - arg2;
                     }
           }

           class Program
           {
                    static void Main(string[] args)
                   {
                              Calculator obj = new Calculator();
                              int addValue=obj.Add(5, 4);
                              Console.WriteLine("5+4=" + addValue);
                              int subValue = obj.Subtract(5, 4);
                              Console.WriteLine("5-4=" + subValue);

                   }
           }
          Output:  5+4=9
                          5-4=1 


Generic And Interface:
  • Example 01 :
          public interface IBaseCalculator<T>
         {
                    T Add(T arg1, T arg2);
                    T Subtract(T arg1, T arg2);
         }
         public class Calculator : IBaseCalculator<int>
        {
                    public int Add(int arg1, int arg2)
                   {
                              return arg1 + arg2;
                   }
                   public int Subtract(int arg1, int arg2)
                  {
                             return arg1 - arg2;
                  }
        }
        class Program
       {
                  static void Main(string[] args)
                 {
                            Calculator obj = new Calculator();
                            int addValue=obj.Add(5, 4);
                            Console.WriteLine("5+4=" + addValue);
                            int subValue = obj.Subtract(5, 4);
                            Console.WriteLine("5-4=" + subValue);

                 }
       }
       Output:  5+4=9
                       5-4=1


Generic Methods:

  • Example 01 :
         class Program
         {
                      static void Swap<T>(ref T tFirstParam, ref T tSecondParam)
                      {
                                T tempValue;
                                tempValue = tFirstParam;
                                tFirstParam = tSecondParam;
                                tSecondParam = tempValue;
                      }

                      static void Main(string[] args)
                     {
                                int firstValue = 10;
                                int secondValue = 20;
                                Console.WriteLine("Before swap : firstValue={0}  and secondValue={1}",                                                       firstValue,   secondValue);
                                Swap<int>(ref firstValue,ref secondValue);
                                Console.WriteLine("After swap : firstValue={0} and secondValue={1}",                                                          firstValue, secondValue);

                                string firstName = "Sani";
                                string lastName = "Talukder";
                                Console.WriteLine("Before swap : firstName={0} and lastName={1}",                                                            firstName, lastName);
                                Swap<string>(ref firstName, ref lastName);
                                Console.WriteLine("After swap : firstName={0} and lastName={1}",                                                              firstName, lastName);
                                Console.ReadLine();
              }
          }

       Output:  


               

Tuesday, December 2, 2014

Access Modifier in c#


  • To hide or encapsulate particular member or type outside the class scope or   to expose particular member or type outside the class scope, then we have to use access modifiers.
Figure

Tuesday, November 25, 2014

Return Anonymous Type from method in C#

Overview:

  • System.Object in the only way to return an anonymous type from a method (because anonymous types are really anonymous).
  • Anonymous  type is extremely useful in linq queries because it allow you to construct type with several properties without declaring the type .
  • We have to use dynamic keyword to get return object ( anonymous type ) from method.

Example:

  • public static object MyMethod()
     {
                return new { firstName = "Saniul", lastName = "Naim" };
     }

      static void Main(string[] args)
      {
                dynamic obj = MyMethod();
                Console.WriteLine(obj.firstName);
                Console.WriteLine(obj.lastName);

                Console.ReadLine();
       }
                    
                                                                                                                                                                                                                                                                        

 Alternavite Idea:

  • If we dont want to use dynamic keyword then we have to use casting.
               public static object MyMethod()
               {
                     return new { firstName = "Saniul", lastName = "Naim" };
               }

               static void Main(string[] args)
              {
                    object obj = MyMethod();

                     var varOjb = Cast(obj, new { firstName = "", lastName = "" });
                     Console.WriteLine("{0} {1}", varOjb.firstName, varOjb.lastName);

                     Console.ReadLine();
              }

              static T Cast<T>(object objParam, T typeName)
             {
                     return (T)objParam;
              }

Note:

  •  Sometime Tuple is very useful:

            public static Tuple<string, string> TupleMethod()
            {
                return Tuple.Create("Saniul", "Naim");
            }

            static void Main(string[] args)
            {
                var obj = TupleMethod();
                Console.WriteLine(obj.Item1);
                Console.WriteLine(obj.Item2);
                Console.ReadLine();
            }
     

    Tuesday, October 28, 2014

    Data Vs Information

    • Data is all the bits - the facts, the figures, the snippets and quotes and the raw pieces that can be put together and pulled apart in many different ways.
    • Information, is the application of the data as something meaningful and valuable.
    • Data alone cannot be called information.
    • Data and process are necessary to create information.
    • The business process, the logic and flow, the sequence of operations; these are all the things that turn data into information.
    • Information have in our system, to transform data into meaningful and valuable.

    Note: 
    • Remember, data and process, neither of them are sufficient on there own.

    Thursday, October 23, 2014

    Abstraction And Encapsulation


    Encapsulation:
    • The internal representation of an object is generally hidden from view outside of the object's definition. 
    • Encapsulation, refers to an object's ability to hide data and behavior that are not necessary to its user.
    •  Classes, Properties and Access Modifiers are tools to provide encapsulation, in c#.
    • Its hiding information details from the caller.
    • Its hiding implementation.
    • Its hiding data like using getter and setter etc.
    • Encapsulation is not just private fields with public properties, but it is both the data and the process (or behavior) being hidden or wrapped up in an implementation that is not exposed to the outside world.
    • We also hidden, the process of converting the data into information. So we say that, we encapsulate the data and the process, crating an object that has both data and behavior.
    • A human being, is not just height,width,eye color,hair color and other data points. A human is also a set of behaviors (influenced by many things, including genetics,life experience etc ) which make each of us unique.
    • it's used to restrict access to the members of a class.
    • Any object that stores details of that object. Example Employee object may have Name, EmployeeId, Salary information etc. By using encapsulation, Employee object can expose the data (ex. Name,EmployeeId) and methods (ex. GetSalary()) necessary for using the object,  while hiding its irrelevant fields and methods from other objects. Here all users could access basic information about an employee while restricting salary information.
    Exposing a solution to a problem without requiring the consumer to fully understand the problem domain.
    Abstraction:
    •  Abstraction means to show only necessary details to the client of the object.
      • Specific solution for a problem, we can use abstraction and we can re-use this solution for the same domain or even for different domain.
      • So we can say that, for re-usability  we use abstraction.
       
    • Interfaces, Abstract classes or Inheritance and Polymorphism are tools to provide abstraction, in c#.
    • Abstraction means -  hiding implementation using abstract class or interface etc..
    • Abstract class provide abstraction but How? 
               Ans: In .net framework, we use list or collection. Imagine if .net only implemented a StudentList And TeacherList, that could only hold a list of students and list of teachers. But what if we need department list. So the "list" or "collection" abstracted away from student,teacher and department. The list or collection by itself is an abstract concept.  


    Abstraction Vs Encapsulation:
    • Abstraction allows making relevant information visible and encapsulation enables a programmer to implement the desired  level of abstraction.
    • Abstraction is a technique that helps up identify which specific information should be visible and which information should be hidden. Encapsulation is then the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to visible. -Edward V. Berard
    .Net design guideline is that, data should be exposed via properties. 
    Client of the object or Outside of the object means when we use reference of object then it will show only necessary methods and properties. And hide methods which are not necessary.

    Monday, August 25, 2014

    Change file from being flagged as a 'system file' back to 'normal' state on windows 7


    "System files" in Windows 7 are files tagged with the following two attributes:
    • Archive
    • System
    "Hidden system files" in Windows 7 are files tagged with the following three attributes:
    • Archive
    • Hidden
    • System
    To reset "System files", simply run the following command:
         attrib -A -S file.ext
    To reset "Hidden System files", run the following:
         attrib -A -H -S file.ext
    

    Saturday, May 31, 2014

    Polymorphism


    • Polymorphism is one of the principle of object oriented programming.

    Definition :
    • Poly means many and morph means forms. Hence polymorphism means many forms.