Menu Close

Category: Blog

GENERICS IN C#

GENERICS IN C#



GENERICS

Generics are introduced in c# 2.0. Generics allow us to design classes and methods deoupled from the data types.

Generics classes are extresively used by collection classes available in System.Collections.Generic namespace.(Covered in the next session)

One way of making AreEqual() method resuable, is to use object type parameters. Since, every type in .NET directly onherit from System.Object type, AreEqual() method works with any data type, but the probelm is performance degradation due to boxing and unboxing happening.

Also, AreEqual() method is no longer type safe. It is now possible to pass integer for th first parameter, and string for the second parameter.It doesn’t really make sense to compare strings with integers.

So, the problem with using System.Object.type is that
1. AreEqual() method is not type safe
2. Performance degradation due to boxing and unboxing.

————————————————————————————————————————–
using System;
using System.Reflection;

namespace ConsoleApplication4
{
    public class MainClass
    {
        private static void Main()
        {
            bool Equal = Calculator.AreEqual<int>(10,10);
            if (Equal)
            {
                Console.WriteLine(“Equal”);
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine(“Not Equal”);
                Console.ReadLine();
            }
        }

    
    }


    public class Calculator
    {
        public static bool AreEqual<T>(T Value1, T Value2)
        {
            return Value1.Equals(Value2);
        }

    }
}

Share this:

LATE BINDING USING REFLECTIONS IN C#

EARLY V/S LATE BINDING IN C#

Difference between early and late binding:


1.Early binding can flag errors at compile time. With late binding there is a risk of run time exceptions.

2. Early binding is much better for performance and should always be preferred over late binding. Use late binding only when working with an objects that are not available at compile time.

3. I think 95% of people use early binding over late binding because of late binding is going to be compiled properly at compile time but it will through exception at Runtime “if there is any errors”, so early binding is better as it warns the programmer with “wiggly sign” at compile time itself, it does not allow to compile the program.



using System;
using System.Reflection;

namespace ConsoleApplication4
{
    public class MainClass
    {
        private static void Main()
        {
// LATE BINDING STARTS HERE
            Assembly executingAssembly = Assembly.GetExecutingAssembly();

            Type customerType = executingAssembly.GetType(“ConsoleApplication4.Customer”);


            object customerInstance = Activator.CreateInstance(customerType);


          MethodInfo getFullNameMethod =  customerType.GetMethod(“GetFullName”);


          string[] parameters = new string[2];

          parameters[0] = “Malla”;
          parameters[1] = “Tech”;

         string fullName = (string)getFullNameMethod.Invoke(customerInstance, parameters);

         Console.WriteLine(“Full Name = {0}”, fullName);
         Console.ReadLine();

// LATE BINDING ENDS HERE.

            ///     Early Binding 
        //    Customer C1 = new Customer();
        //    string fullname = C1.GetFullName(“Malla”, “Tech”);
        //    Console.WriteLine(“Full Name = {0}”, fullname);
        //    Console.ReadLine();
        }
    }


    public class Customer
    {
        public string GetFullName(string FirstName, string LastName)
        {
            return FirstName + ” ” + LastName;
        }

    }
}

Share this:

REFLECTIONS IN C#

REFLECTIONS IN C#


“is the ability of inspecting assemblies’ metadata at runtime. it is used to find all types in an  assembly and /or dynamically invoke methods in an assembly.”


Uses of reflection:

1. When you drag and drop a button on a win forms or asp.net application. The properties window uses reflection to show all the properties of the Button class. So, reflection is extensivley used by IDE or a UI designers.


2. Late binding can be achieved by using reflection. You 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.

3. Consider an example where we have two alternate implementations of an interface. You want to allow the 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 the config file, and instantiate an instance of that class. This is another example for late binding using reflection.

————————————————————————————————————————–
using System;
using System.Reflection;

namespace ConsoleApplication4
{
    public class MainClass
    {
       
        private static void Main()
        {    
            Type T = Type.GetType(“ConsoleApplication4.Customer”);
            Console.WriteLine(“Full Name = {0}”, T.FullName);
            Console.ReadLine();
            Console.WriteLine(“Just the Name = {0}”, T.Name);
            Console.WriteLine(“Just the Namespace = {0}”, T.Namespace);

            Console.ReadLine();

            Console.WriteLine(“Properties in Customer”);
            PropertyInfo[] properties = T.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                Console.WriteLine(property.PropertyType.Name + ” ” + property.Name);
                Console.ReadLine();
            }

            Console.ReadLine();

            Console.WriteLine(“methods in Customer class”);
            MethodInfo[] methods = T.GetMethods();
            foreach (MemberInfo method in methods)
            {
                Console.WriteLine(method.ReflectedType.Name + ” ” + method.Name);
                Console.ReadLine();
            }


            Console.ReadLine();

            Console.WriteLine(“Constructor in Customer class”);
            ConstructorInfo[] constructors = T.GetConstructors();
            foreach (ConstructorInfo constructor in constructors)
            {
                Console.WriteLine(constructor.Name);
                Console.ReadLine();
            }
        }
    }
}
    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public Customer(int ID, string Name)
        {
            this.Id = ID;
            this.Name = Name;
        }
        public Customer()
        {
            this.Id = -1;
            this.Name = string.Empty;

        }
        public void PrintID()
        {
            Console.WriteLine(“ID= {0}”, Id);
            Console.ReadLine();
        }
        public void PrintName()
        {
            Console.WriteLine(“Name ={0}”, Name);
            Console.ReadLine();
        }
    }


==============================================























Share this:

ATTRIBUTES IN C#

Attributes

Attributes allow you to add declarative information to your programs. This information can then be queried at runtime using reflection

There are several Pre-defined attributes provided by .NET.It is also possible to create your own Custom Attributes.

A few pre-defined attributes with in the .NET framework.
obsolete    – Marks types and type members outdated
WebMethod  – To expose a method as an XML Web service method
Serializable  – Indicates that a class can be serialized


It is possible to customize the attributes using parameters
An attributes is a class that inherits from SYSTEM.ATTRIBUTES base class.
————————————————————————————————————————–

using System;
using System.Collections.Generic;

namespace ConsoleApplication4
{
    public class MainClass
    {
        private static void Main()
        {
            Calculator.AddNumber(new List<int>() {10,20, 30});
           

        }
    }

    public class Calculator
    {
        [Obsolete(“Use(List<int> Numbers)Method”,true)]
        public static int AddNumber(int FirstNumber, int SecondNumber)
        {
            return FirstNumber + SecondNumber;
        }

        public static int AddNumber(List<int> Numbers)
        {
            int Sum = 0;
            foreach (int Number in Numbers)
            {
                Sum = Sum + Number;
            }
            return Sum;
        }
    }

}

Share this:

ACCESS MODIFIERS FOR TYPES(CLASSES) IN C#

CLASSES, STRUCTURES, INTERFACES, DELEGATES WILL HAVE TYPES AND CAN ONLY USE INTERNAL OR PUBLIC ACCESS MODIFIERS

using System;
namespace ConsoleApplication4
{
    public class AssemblyOne
    {
        public void PrinID()
        {
            Console.WriteLine(“print this is a types example”);
        }
    }
}
// default  is internal for type classes like classes, structures, interfaces, delegates, etc..
// default  is private for type members like fields, properties, methods, etc 
using System;
using AssemblyOne;
namespace ConsoleApplication4
{
internal class AssemblyTwo 
    {
        AssemblyOne instance = new AssemblyOne();
        instance.xxxxxx     = xyz;
    }
}
Share this: