Friday, 14 August 2015

Partial in C# - Partial class and Partial methods

It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.

Creating partial class :


  • All the part of class spread across different files must use the partial keyword.
  • All part of class must have same access modifiers.
  • If any of the part is declared abstract, then entire type is considered abstract.
  • If any of the part is declared sealed, then entire type is considered sealed.
  • If any of part inherit a class , then entire type inherit that class.
  • Different part of partial class can't specify different base class.
  • Different part of partial class can specify different base interface.
  • Any member declared in a partial definition are available to all the other parts of the partial class.

Partial Method :


  • A partial  class and structure can contain partial method.
  • Implementation of partial method is optional, If we compile it without body, it will compile.actually compiler ignore partial method declaration and its call until it's body is defined.
  • Partial method is private by default.partial method can't have any modifier like access modifiers, static, abstract, virtual etc.
  • Without declaration of partial method you can't provide definition for partial method, it will give compile time error.
  • A partial method return type is must be void, including any other return type is a compile time error.
  • signature of declaration and definition of partial method must be same.
  • Partial method can be implemented only once otherwise compile time error.


class Program
    {
        public static void Main()
        {

            test obj ;
            obj.hello();

            Console.Read();          

        }
    }  
    public partial struct test
    {
        partial void partialMethod();
        public void hello()
        {
            partialMethod();
        }
    }
    public partial struct test
    {
        partial void partialMethod()
        {
            Console.WriteLine("Hello");
        }      
    }

Wednesday, 12 August 2015

Invoke method dynamicly in C# - Late Binding using Reflection

Late binding is associating a method with an object at runtime.At compile time compiler does not know about this association.

Reflection is one of the way to achieve late binding.

In following example we will inspect the assembly, create object of class at runtime, find method of this class using reflection and call this method using created object.

namespace TypeCastingRND
{  
    public class Program
    {
        public static void Main()
        {
             // Get current Assembly
            Assembly executedAssembly = Assembly.GetExecutingAssembly();          
            Type studentType = executedAssembly.GetType("TypeCastingRND.Student");

           // Create instance of Student class
           object studentInstance = Activator.CreateInstance(studentType);

            // Get method using reflection
            MethodInfo methodName = studentType.GetMethod("StudentFullName");

            //Create parameter array
            string[] parameters = new string[2];
            parameters[0] = "Rahul";
            parameters[1] = "Saini";

            //Invoke method and get return 
            string StudentName=(string)methodName.Invoke(studentInstance, parameters);
            Console.WriteLine("Student Name : " + StudentName);

            Console.Read();
        }
    }

    public class Student
    {
        public string studenFirstName { get; set; }
        public string studenLastName { get; set; }
        public Student()
        {
       
        }
        public string StudentFullName(string FirstName,string LastName)
        {
            return FirstName + " " + LastName;
        }
    }  
}

Output :
Student  : Rahul Saini

Reflection in C#

Reflection is the way of inspecting an assemblies's metadata at runtime. it is used to find all types in an assembly and dynamically invoke methods of an assembly.With the help of reflection you can find what classes, methods, propertied, constructors etc. assembly contains.You can also know what any method is expecting and what will method return and many more.

Uses of reflection :
  • When you drag and drop a button on a win form or an asp.net application.the property window uses reflection to show all the properties of the button class so reflection is used by IDE or UI designers .
  • When you use ILDASM command to inspect a assembly, internally it's also using reflection..
  • Late binding can be achieved by reflection can use reflection to dynamically create an instance of a type, about which we don't have any information at compile time. so reflection enables you to use code that is not available at compile time.
  • Suppose you have two alternate implementation of an interface. you want to allow user to pick one or the other using a config file. with reflection, you can simply read the name of the class whose implementation you want to use from config file, and instantiate an instance of that class. this is another example of late binding using reflection.
Following is the example of reflection :


using System.Reflection;

namespace Logicsmaze
{
     public class Student
    {
        public string studenName { get; set; }
        public int rollno { get; set; }
        public int parentsIncome { get; set; }

        public Student()
        {
       
        }

        public Student(int rollNo,string name,int Income)
        {
            this.rollno = rollNo;
            this.studenName = name;
            this.parentsIncome = Income;
        }

        public static void Scholarship(List<Student>lstStudent)
        {
           
        }
    }

    class Program
    {
        public static void Main()
        {
            //Type t = Type.GetType("Logicsmaze.Student");  or
            Type t = typeof(Student);

            Console.WriteLine("...............Class Detail..........");
            Console.WriteLine(t.Name);
            Console.WriteLine(t.FullName);
            Console.WriteLine(t.Namespace);

            Console.WriteLine();
            Console.WriteLine("...........Properties in Student class........");
            PropertyInfo[] properties = t.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                Console.WriteLine(property.Name + " is type of: " + property.PropertyType.Name);
            }
            Console.WriteLine();
            Console.WriteLine("...........Methods in Student class........");
           MethodInfo[] methods = t.GetMethods();
           foreach (MethodInfo method in methods)
           {
               Console.WriteLine(method.Name + " has return type : "+method.ReturnType.Name);
           }

           Console.WriteLine();
           Console.WriteLine("...........Constructors in Student class........");
           ConstructorInfo[] constroctors = t.GetConstructors();
           foreach (ConstructorInfo constructor in constroctors)
           {
               Console.WriteLine(constructor.ToString());
           }

            Console.Read();
        }
    }    
}

Output : 


Wednesday, 5 August 2015

Which one will be Called!!! - Calling Overloaded Functions with Float, Decimal, Double and int

class Program
    {
        static void Main(string[] args)
        {
            double dbl = 10;
            float flt = 10;
            decimal dml = 10;


            FunctionWithOverload(10);               // Function with int called
            FunctionWithOverload(10f);              // Function with float called
            FunctionWithOverload(10.56);            // Function with double called
            FunctionWithOverload(.25);              // Function with double called
            FunctionWithOverload(flt);              // Function with float called
            FunctionWithOverload(dbl);              // Function with double called
            FunctionWithOverload(dml);              // Function with decimal called
            FunctionWithOverload(10.25f);           // Function with float called
            FunctionWithOverload(10.253m);          // Function with decimal called
            FunctionWithOverload(10.2534585685m);       // Function with decimal called
            FunctionWithOverload(10.2535698455);        // Function with double called
            FunctionWithOverload(10.2535698f);          // Function with float called

            Console.ReadLine();
        }
        public static void FunctionWithOverload(object var_obj)
        {
            Console.WriteLine("Function with Object called :" + var_obj);
        }
        public static void FunctionWithOverload(float var_float)
        {
            Console.WriteLine("Function with float called :" + var_float);
        }
        public static void FunctionWithOverload(decimal var_dcl)
        {
            Console.WriteLine("Function with decimal called :" + var_dcl);
        }
        public static void FunctionWithOverload(double var_dbl)
        {
            Console.WriteLine("Function with double called :" + var_dbl);
        }
        public static void FunctionWithOverload(int var_int)
        {
            Console.WriteLine("Function with int called :" + var_int);
        }
    }

Output : 

Tuesday, 4 August 2015

Examples of Implicit and Explicit Casting of datatypes in C#


Case 1 : 
Suppose you have a class, class having some properties/data members.
When you instantiate this class, all the data members of this class will be initialized with it's default values or by null.

  • If data member of class is value type, it will be initialize by its default value like int variable initialize with zero, float with 0.0, bool with false etc.
  • If data member of class is reference type, it will be null like string variable, array, object of other class will also be null.
Please refer following example :

 public class Class1
    {
        public int var_int;
        public string var_string;
        public float var_float;
        public bool var_bool;
        public string[] var_str_arr;
        public int[] var_int_arr;
        public Class2 var_class2;
    }
    public class Class2
    {
        public int var_int;
        public string var_string;
        public float var_float;
    }

  class Program
    {
        static void Main(string[] args)
        {            
            Class1 objclass1 = new Class1();   

            Console.WriteLine(objclass1.var_int);        // Output will be 0              
            Console.WriteLine(objclass1.var_float);      // Output will be 0.0
            Console.WriteLine(objclass1.var_bool); // Output will be false
           Console.WriteLine(objclass1.var_string);    // var_string will be null
            Console.WriteLine(objclass1.var_str_arr); // var_str_arr will be null
            Console.WriteLine(objclass1.var_int_arr); // var_int_arr will be null
            Console.WriteLine(objclass1.var_class2); // var_class2 will be null
            
            Console.ReadLine();
        }
    }
   

Case 2 : Casting of variables

class Program
    {
        static void Main(string[] args)
        {
            int i;
            float flt;
            double dbl;
            decimal deci;

            i = 10;
            flt = 10.10f;
            dbl = 20.20;
            deci = 12.456m;

            Console.WriteLine("...........Convert to int...........");
            //i = flt;                              //Error : can not implicitly convert type float to int
            i = (int)flt;                          //Explicit casting
            Console.WriteLine(i);
            //i = dbl;                            //Error : can not implicitly convert type double to int
            i = (int)dbl;                         //Explicit casting
            Console.WriteLine(i);
            //i = deci;                           //Error : can not implicitly convert type decimal to int
            i = (int)deci;                        //Explicit casting
            Console.WriteLine(i);

            i = 10;
            flt = 10.10f;
            dbl = 20.20;
            deci = 12.456m;

            Console.WriteLine("...........Convert to float...........");
            flt = i;
            Console.WriteLine(flt);
            //flt = dbl;                        //Error : can not implicitly convert type double to float
            flt = (float)dbl;
            Console.WriteLine(flt);
            //flt = deci;                      //Error : can not implicitly convert type decimal to float
            flt = (float)deci;
            Console.WriteLine(flt);

            i = 10;
            flt = 10.10f;
            dbl = 20.20;
            deci = 12.456m;

            Console.WriteLine("...........Convert to double...........");
            dbl = i;
            Console.WriteLine(dbl);
            dbl = flt;                     
            Console.WriteLine(dbl);            
            //dbl = deci;                       //Error : can not implicitly convert type decimal to double
            dbl = (double)deci;
            Console.WriteLine(dbl);

            i = 10;
            flt = 10.10f;
            dbl = 20.20;
            deci = 12.456m;

            Console.WriteLine("...........Convert to decimal...........");
            deci = i;
            Console.WriteLine(deci);
            //deci = flt;                                 //Error : can not implicitly convert type float to decimal
            deci = (decimal)flt;
            Console.WriteLine(deci);
            //deci = dbl;                             //Error : can not implicitly convert type double to decimal
            deci = (decimal)dbl;
            Console.WriteLine(deci);
                                  
            Console.ReadLine();

        }

Output : 

Case 3 :  Calling of function by changing it's argument type also depends on implicit conversion of data types.


class Program
    {
        static void Main(string[] args)
        {
            int i;
            float flt;
            double dbl;
            decimal deci;

            i = 10;
            flt = 10.10f;
            dbl = 20.20;
            deci = 12.456m;

            //******Passing expected argument******
            CheckIntFloatDecimalDouble(i, flt, deci, dbl);          // Work Fine

            //******Changing first(integer) argument******
            //CheckIntFloatDecimalDouble(flt, flt, deci, dbl);      // Error : has some invalid argument

            //******Changing second(float) argument******
            //CheckIntFloatDecimalDouble(i, dbl, deci, dbl);        // Error : has some invalid argument
            CheckIntFloatDecimalDouble(i, i, deci, dbl);            // Work Fine

            //******Changing third(decimal) argument******
            //CheckIntFloatDecimalDouble(i, flt, flt, dbl);         // Error : has some invalid argument
            //CheckIntFloatDecimalDouble(i, flt, dbl, dbl);         // Error : has some invalid argument

            //******Changing fourth(double) argument******
            CheckIntFloatDecimalDouble(i, flt, deci, flt);          // Work Fine
            //CheckIntFloatDecimalDouble(i, flt, deci, deci);       // Error : has some invalid argument
        
            Console.ReadLine();
        }
        public static void CheckIntFloatDecimalDouble(int int_var, float float_var, decimal deci_var, double dbl_var)
        {
            Console.WriteLine(int_var);
            Console.WriteLine(float_var);
            Console.WriteLine(deci_var);
            Console.WriteLine(dbl_var);
        }
    }