Introduction to C# delegate and multicast delegate

What is a C# delegate?

The C# delegate is a reference data type that defines the method and their signature. The delegate stores the address of one or more methods. When a delegate for a method assigned, it behaves exactly like the method. It can be invoked like any other method with parameters and return value.
A delegate simply stores the reference of the methods with the same signatures such as return type and parameter list. A delegate can be invoked as like a class by creating an object for the delegate. The delegate object allows running the methods at run time without invoking it directly.

Usage of delegate:

When an event needs to be used then delegates can be used. Multicast delegates can be used for invoking many events at a time. When a class need to have more than one implementation of the method and to encapsulate a static method.

Refer for when to use delegates and interfaces -> https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/ms173173(v=vs.100)

The Ultimate Managed Hosting Platform

Declaring a delegate:

The System.Delegate class is the base class for the delegate declaration. The delegate keyword is used to declare a delegate. The return type and parameters should same as the methods.

Eg:

public delegate int CalDelegate(int num1,int num2);

Instantiation and invoking delegates:

To instantiate a delegate, an instance is created similar to how a class instance is created. When a delegate is instantiated, the address of the method is stored in the instance.


Eg:
Calculator cal=new Calculator();
CalDelegate sumDel=new CalDelegate(cal.sum);
CalDelegate mulDel=new CalDelegate(cal.multiply);


CalDelegate is the delegate created and the sumDel is the delegate instance instantiated to CalDelegate with the reference to the sum() method in cal instance and mulDel is for reference of multiply() method.


To invoke the delegate, calling the delegate instance with the parameter list referenced by the delegate with the same data type.


Eg:
sumDel(10, 12);

mulDel(10,12);

using System;

public delegate int CalDelegate(int num1,int num2);
public class Calculator
{
	public int sum(int num1,int num2)
	{
		return num1+num2;
	}
	public int multiply(int num1,int num2)
	{
		return num1*num2;
	}
}
public class Program
{
	public static void Main()
	{
		Calculator cal=new Calculator();
		CalDelegate sumDel=new CalDelegate(cal.sum); // sumDel for sum() reference
		CalDelegate mulDel=new CalDelegate(cal.multiply); //mulDel for multiply() reference
		Console.WriteLine(sumDel(10,12));
		Console.WriteLine(mulDel(10,12));
	}
}

Output:

22

120

Multicast delegates:

To have a reference of more than one method in delegate multicast delegates is used. This mainly used in the multi-event invocation. The += operator is used to add the methods referred to delegate and -= operator is used to remove the methods. The methods are called in First-In-First-Out(FIFO) order.

Remember when using multicast delegates use void as return types because the use of multiple methods will clash in return type. So void is safe to avoid runtime exception.

Eg:

CalDelegate simpleDel=new CalDelegate(cal.sum);

simpleDel += new CalDelegate(cal.multiply);

simpleDel -= new CalDelegate(cal.sum);

using System;

public delegate void CalDelegate(int num1,int num2);
public class Calculator
{
	public void sum(int num1,int num2)
	{
		Console.WriteLine(num1+num2);
	}
	public void multiply(int num1,int num2)
	{
		Console.WriteLine(num1*num2);
	}
}
public class Program
{
	public static void Main()
	{
		Calculator cal=new Calculator();
		CalDelegate simpleDel=new CalDelegate(cal.sum);
		simpleDel+=new CalDelegate(cal.multiply); //multicasting using += operator
		simpleDel(10,12);
	}
}

Output:

22

120

The above delegate example is used with multicast delegates in which the firstsum()method is referenced to thesimpleDeldelegate. Thenmultiply()method is added to multicast using += operator. To remove the methods from delegate simply use -= operator. As said multicast delegate run in FIFO, firstsum()delegate reference is run and thenmultiply()with output 22 and 120 respectively.

For documentation of delegates refer -> https://docs.microsoft.com/en-in/dotnet/api/system.delegate?view=netcore-3.1

In next post, I will explain synchronous delegate, asynchronous delegate and covariance and contravariance delegates.

For my other C# archives -> Go.

If you enjoy my post please share it and if any suggestion please comment on it.

 1,474 total views

Learn how to create C# ArrayList

ArrayList in C#

ArrayList is a type of non-generic collection framework available in the .Net framework for creating an array of objects list using C# language. The non-generic refers to that we don’t need to mention the data type of the array list. This array list can be dynamically defined of what size wanted. Unlike array initialization, we don’t need to specify the size of the list. It dynamically allocates size as we add or remove an element in the array list. Since it is a non-generic collection, the elements added to the array are stored as an object.

The basic operation we do in ArrayList add, remove, count, sort list. We can also do many operations such as reverse the ArrayList, get the index value of elements etc.

To view full properties and methods please refer: https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=netcore-3.1

Create ArrayList

We can create an ArrayList using the ArrayList class and new operator.

using System;
using System.Collections;
					
public class Program
{
	public static void Main()
	{
		//array1 array list is created using new operator.
		ArrayList array1=new ArrayList();
		
	}
}

Add() method

Add(Object value) method will add the element to the ArrayList one after another.

using System;
using System.Collections;
					
public class Program
{
	public static void Main()
	{
		
		ArrayList array1=new ArrayList();
		//adding 5 elements to array1 using ADD() method.
		array1.Add("Element1");
		array1.Add("Element2");
		array1.Add("Element3");
		array1.Add("Element4");
	}
}

Remove()

Remove(Object value) method will remove the element mentioned.

using System;
using System.Collections;
					
public class Program
{
	public static void Main()
	{
		
		ArrayList array1=new ArrayList();
		//adding 5 elements to array1 using Add() method.
		array1.Add("Element1");
		array1.Add("Element2");
		array1.Add("Element3");
		array1.Add("Element4");
		
		Console.WriteLine("Before removing");
		//output of array1 before remove
		foreach(string str in array1)
		{
			Console.WriteLine(str);
		}
		
		//removing Element4 and Element3 from array1 arraylist using Remove().
		array1.Remove("Element3");
		array1.Remove("Element4");
		
		Console.WriteLine("After removing");
		//output of array2 after remove
		foreach(string str in array1)
		{
			Console.WriteLine(str);
		}
		
	}
}

Output:

Before removing
Element1
Element2
Element3
Element4
After removing
Element1
Element2

In the above program, foreach used to iterate through array1 ArrayList to display the elements.

Using indexers [<index_number>] we can access the elements in the array list.

The output shows the elements in array1 before and after remove() method is used.

  • To get the no of elements in the ArrayList use Count property.
  • To sort the ArrayList use Sort() method.
  • To check an element is contained in the ArrayList use Contains() method.
		//get the count of elements in array1
		Console.WriteLine(array1.Count);
		//to sort the array1
		array1.Sort();
		//check element contains in an array and return true if it contains the element else return false
		Console.WriteLine(array1.Contains("Element1"));

Some other methods are

Insert(int index,object value)

  • Use to insert the element at the given index.

RemoveAt(int index)

  • Removes the element at the given index.

BinarSearch(object value)

  • Search for an object using binary search.

Clear()

  • Clear all the elements in ArrayList.

IndexOf(object value)

  • Gets the index of the particular object.

For other operations refer .NET docs.


For other C# archives -> Go.

For my other programming archive -> Go.

 1,404 total views

C# interface and multiple interfaces tutorial

What is interface?

The definitions for a group of related functionalities that a non-abstract class or struct can declare is called an interface. The interface is another way of abstraction in C#. The interface is like the abstract class but it only contains the methods definitions, whereas the abstract class contains all methods, fields, constants definitions. Unlike the abstract class, the interface cannot have a constructor. The interface methods should be abstract and public. The interface only provides the definition for the methods. In C# multiple inheritances cannot be done in class but by means of the interface.

The interface in C#:

  • Members in the interface should be abstract and public only no other access specifier used.
  • By interface, we can’t able to create an object like an abstract class.
  • Interface only define the methods, the class needed to override and implement those methods.
  • The interface doesn’t contain a constructor.
  • The interface contains methods and properties but not fields.

Implementation of C# interface:

The interface keyword used to implement the interface. We can also implement multiple interfaces for a single class in C#. It’s suggested to use I before every interface name to identify it has the interface. To use an interface in a class we use (:) to access the interface. For example, demo as interface name then use IDemo.

Syntax:

interface <interface_name>
{
    method definition;
}
class <class_name>:<interface_name>
{
interface_method declaration;
}

Example:

using System;
	
interface IDemo1
{
	void simpleInterface();
}

public class Demo:IDemo1{
	public void simpleInterface(){
		Console.WriteLine("Implementation of Idemo1 interface");
	}
}
public class Program
{
	public static void Main()
	{
		Demo d=new Demo();
		d.simpleInterface();
		Console.ReadLine();
	}
}

Here I implement an interface called IDemo1. Then I use the IDemo1 interface in Demo class using the operator (:). Then I implement the interface method simpleInterface by declaring an output statement which displays Implementation IDemo1 interface.

Multiple interfaces:

To use multiple interfaces, simply use a comma between the interfaces name in class. The above program can be implemented as multiple interfaces with another interface called Idemo2.

using System;
	
interface IDemo1
{
	void simpleInterface1();
}

interface IDemo2
{
	void simpleInterface2();
}
public class Demo:IDemo1,IDemo2{
	public void simpleInterface1(){
		Console.WriteLine("Implementation of Idemo1 interface");
	}
	
	public void simpleInterface2(){
		Console.WriteLine("Implementation of Idemo2 interface");
	}
}
public class Program
{
	public static void Main()
	{
		Demo d=new Demo();
		d.simpleInterface1();
		d.simpleInterface2();
		Console.ReadLine();
	}
}

From C# 8.0 onwards we can implement a default implementation for the interface methods itself. We can also use other access specifiers such as private, protected, internal, public, virtual, abstract, override, sealed, static, extern. We can also implement static methods in interfaces.

For reference https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods#drawbacks

For my other programming post -> Go.

 711 total views