Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, December 1, 2011

Delegates in C#

Delegates is a type that reference Method. When it assigned by a method it behaves exactly same as that method. It can be used as parameters and can be returned a value. So it has same what are the methods have.
Delegates makes is possible to programmatically change method calls, and plug new codes in to existing classes. For these you need to know what are the method matches delegate’s signature and its return type. Delegates are similar to C++ function pointers but delegates type safe and Object Oriented. Methods don’t need to match the delegate signature exactly.
What is Covariance and Contravariance in Delegates ?
Covariance and Contravariance provides kind of flexibility when matching the method signature with delegate type that is defined.
Covariance permits a method to have a more derived return type than what is defined when the delegate define. Contravariance permits a method to have less derived parameter types than in the delegate type.

A delegate is a type it encapsulates a method see below example:
        // Define the Delegate
        public delegate void TestDelegate(string Message);

        // Creating a method with string argument
        public static void DisplayMessage(string Message)
        {
            Console.WriteLine(Message);
            Console.ReadKey(); 
        }

        static void Main(string[] args)
        {
            // Instantiate the delegate and encapsulates the method "DisplayMessage"
            TestDelegate Test = DisplayMessage;

            // call the delegate
            Test("This is my delegate method");
        }

 This is very simple example but delegate can used in advance way rather this. The instantiated delegate is an object, it can be passed as parameter, or assign to a property. When a delegate is use in this way the code using by the delegate does not need any knowledge of the method being used. This is similar functionality provide by interface encapsulation.
What is Multicasting?
In a delegate you can have more than one method to invoke, you can assign method to a delegate using “=” and you can add method to a delegate where it has assigned a method to invoke by using “+” if you want you can remove assigned method from a delegate where it has more methods to invoke by using “-“. This is called as multicasting.

Multicasting example:

namespace Delegates_Test2
{
    delegate void Del();


    class Simple
    {
        public void MethodA()
        {
            System.Console.WriteLine("Message from the method A.");
        }

        static public void MethodB()
        {
            System.Console.WriteLine("Message from the method B.");
        }

    }
}

 namespace Delegates_Test2
{
    class Program
    {
        static void Main(string[] args)
        {
            Simple sc = new Simple();

            // Map delegate to the method: A
            Del d = sc.MethodA;
         

            // Map method: B with multicasting
            d += Simple.MethodB;
           
            d(); // Both methods are excute here

            Console.ReadKey(); 

        }
    }
}


Generic Delegates
The delegate can define its own generic type parameters.
How to define:

public delegate void MyDelegate<T>(T item);
Generic delegate example:
namespace Generic_Delegate
{
    //Generic Delegate define here with return value of T, and both T arguments
    public delegate T Calculator<T> (T arg1, T arg2);

    class MathUtility
    {
    
    // Generic method to execute with Two generic argument values and one generic  methods  
        public static void Calculate<T>(T[] values1, T[] values2, Calculator<T> t)
        {
            for (int i=0; i < values1.Length; i++)
            {   // execute the T method with two of T arguments
                values1[i] = t(values1[i],values2[i]);
                //And assigning results to First parameter
     
            }
        }
    }
}



namespace Generic_Delegate
{
    class Program
    {
        // My method to find  square value
        static int FindSquareValue(int x, int y)
        {
            // Your method's implementation
            return (x * y); // Your method have defined to return the results
        }

        // My Method to find dividence with first value by second value
        static double FindDividence(double a, double b)
        {
            // Your method's implementation
            return (a / b);  // Your method have defined to return the results
        }
          
        static void Main(string[] args)
        {
            // To get Square
            int[] height = { 10, 5, 8 };
            int[] width = { 4, 3, 6 };

            MathUtility.Calculate(height, width, FindSquareValue); // Dynamically hook with
                                                                   // FindSquare method
            // You're only passing the both values and method
          

            Console.WriteLine("Display Square Values..."); 
           
            foreach (int i in height)
            {
                Console.WriteLine(i.ToString());   
            }
    

           // To get Dividence
            double[] Val1 = { 10, 80, 60 };
            double[] val2 = {8,3,4};

            MathUtility.Calculate(Val1, val2, FindDividence);

            Console.WriteLine("Display Dividence values..."); 

            foreach (double d in Val1)
            {
                Console.WriteLine(d.ToString());  
            }

            Console.ReadKey(); 
        }
    }
}


Hope this documentation may valuable for you!!

Wednesday, September 21, 2011

Generic


C# generics and C++ templates are very similar but they work differently. Generic exist to write code that is reusable across different types.

Let’s imagine we need a stack of integers if we didn’t have generic types, one solution is to hard code a separate version of a class for every required type “IntStack” but when we need stack of string have do the same way “StrStack”. This would cause considerable code duplication.

However this wouldn’t work aAnother solution would be write a stack that is generalizes by using Object as element type.s well hard coded “IntStack” & “StrStack” an “ObjectStack” require boxing & down casting that could not be checked at compile time.

int x = (int)stack.Pop(); // down casting

What we need is both a general implementation of a stack that works for all element type, and a way to easily specialize that stack to a specific element type for increased type safety and reduced boxing and casing.

Generics provide this by allowing parameterize element type.  Stack<T>  has the benefits of both “ObjectStack” and “IntStack”.

Test this example for further understanding.

    class Part
    {
        private string _PartId;
        private string _PartName;
        private string _PartDescription;
        private double _Weight;

        public string PartId { get { return _PartId; } }

        public Part(string PartId, string PartName, string PartDescription, double Weight)
        {
            _PartId = PartId;
            _PartName = PartName;
            _PartDescription = PartDescription;
            _Weight = Weight;

        }

        public override string ToString()
        {
            return string.Format("Part Id: {0}, Part Name:{1}, Part Description:{2}, weight:{3}", _PartId, _PartName, _PartDescription, _Weight);
        }


    }

 

   //the actual indexer, which accepts the generic type
    //note the type must be a class (not a value type)

    class Indexer<T> where T:class
    {
        struct ItemStruct
        {
            public string Key;
            public T value;
            public ItemStruct(string key, T value)
            {
                this.Key = key;
                this.value = value;

            }

        }

        List<ItemStruct> _items = new List<ItemStruct>();

        // T must be a class so that can return null if not found
        public T Find(string key)
        {
            foreach (ItemStruct _ItemStruct in _items)
            {
                if (_ItemStruct.Key == key)
                {
                    return _ItemStruct.value;
                }
            }
            return null;
        }

        public void Add(string key, T value)
        {
            _items.Add(new ItemStruct(key, value));
        }

    }

 
// Programe to Test it

    class Program
    {
        static void Main(string[] args)
        {


            Indexer<Part> indexer = new Indexer<Part>();

            Part p1 = new Part("001", "Mother Board", "Intel Chip set Mother Board", 0.75);
            Part p2 = new Part("002", "Processor", "Intel Core i5", 0.2);

            indexer.Add(p1.PartId, p1);
            indexer.Add(p2.PartId, p2);

            Part p = indexer.Find("002");

            Console.WriteLine(p.ToString());

           
            Console.ReadKey();
        }
    }








Tuesday, September 20, 2011

Structs in C#


Struct is very similar to a class but strcut is value type and class is reference type, .Net supports the value type and reference type unlike Java, in Java you can define only reference type.  Strcuts may leads to good performance where it’s used properly.

Reference types instances allocating in the managed heap and are garbage collected when there are no further references. Value types are allocated in the stack and so allocated memory is reclaimed as soon as their scope ends.  Using a value type instead reference type may result in fewer objects on the managed heap, which results less load to garbage collector (GC) and better performance.

Since for a value type, a compiler by default doesn’t generate a default constructor, struct doesn’t have parameter less constructor. And no finalizer, no virtual members and it derives only from System.ValuType, This System.ValueType may again derives from System.Object .    But structs can implement interfaces, in C# all primitive data types are value type except System.String
However value types have their poor sides too, when passing around big struct costlier than a reference type.

An example of declaring constructors.
    struct Point
    {
       private int x;
       private int y;

        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

An example of calling struct constructors.
              Point point1 = new Point();
            Point point2 = new Point(1,3);

Mapping data flows in Azure Data Factory

  Overview: Data flows are one of the features inside the Azure Data Factory which allows data engineers to develop data transformation logi...