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,567 total views

How to create C# List generics

C# List<T> generics

  • C# List<T> is a strongly typed collection for creating a list of objects of type <T>. 
  • It is similar to ArrayList, we can add, remove, search, sort, manipulate list-objects.
  • In C#, ArrayList is a non-generic collection whereas List<T> is a generic collection.
  • List<T> has high performance than ArrayList and type-safe. 
  • List<T> has similar methods and properties as the ArrayList.

Creating a C# List<T>

  • List<T> is created by using a new operator either it can be empty capacity or specify the size.

Syntax:

List<T> <list_name> = new List<T>(<capacity>);

  • <T> is the type of object to be created like int, float, double etc.
  • <list_name> name of the list.
  • <capacity> is the size of the list which is optional.

Eg:

List<string> List1 = new List<string>();

Adding object to List<T>

  • Add(T obj) method will add the element type <T> in the list on by one.

Eg:

List1.Add(“Element1”);

  • Insert(int index, T obj) method will add the element at the specified index.

Eg:

List1.Insert(1,”Element1”);

Removing object to List<T>

  • Remove(T obj) method will remove the element in the list.

Eg:

List1.Remove(“Element1”);

  • RemoveAt(int index) Removes the element at the specified index.

Eg:

List1.RemoveAt(1);

Get the size of List<T>:

  • Count property is used to get the size of the list.

Eg:

List1.Count();

To sort the List<T>:

  • Use the Sort() method to sort the array in ascending order.

Eg:

List1.Sort();

Accessing the elements in the List<T>

  • The index number can be used to access the elements like an array.

Eg:

List1[0] // accessing element at index 0;

  • To iterate over the List<T>, use foreach function.

Eg:

foreach(string str in List1)

{

Console.WriteLine(str);

}

Example:

using System;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		//create new List<T> of string type using new operator.
		List<string> list1=new List<string>();
		
		//Adding elements using Add(T) method.
		list1.Add("Element1");
		list1.Add("Element2");
		list1.Add("Element3");
		list1.Add("Element4");
		list1.Add("Element5");
		
		
		Console.WriteLine("Printing elements in list1");
		Console.WriteLine("Size of list1: "+list1.Count);//prinitng size of list1 using count
			
		//printing list1 elements using foreach
		foreach(string str in list1)
		{
			Console.WriteLine(str);
		}
		
		//removing 'Element1' 'Element2' using Remove(T) method.
		list1.Remove("Element1");
		list1.Remove("Element2");
		
		Console.WriteLine();
		
		Console.WriteLine("Printing elements in list1 after removing Element1, Element2");
		Console.WriteLine("Size of list1: "+list1.Count);//prinitng size of list1 using count
		
		//printing list1 elements using foreach
		foreach(string str in list1)
		{
			Console.WriteLine(str);
		}
		
		list1.Insert(2,"Element1");//inserting 'Element1' in index 2
		list1.Insert(4,"Element2");//inserting 'Element2' in index 4
		
		Console.WriteLine();
		
		Console.WriteLine("Printing elements in list1 after inserting Element1, Element2");
		Console.WriteLine("Size of list1: "+list1.Count);//prinitng size of list1 using count
		//printing list1 elements using foreach
		foreach(string str in list1)
		{
			Console.WriteLine(str);
		}
		
		list1.Sort();//sorting list1
		
		Console.WriteLine();
		
		Console.WriteLine("Printing elements in list1 after sorting");
		//printing list1 elements using foreach
		foreach(string str in list1)
		{
			Console.WriteLine(str);
		}
		
	}
}

Output:

Printing elements in list1
Size of list1: 5
Element1
Element2
Element3
Element4
Element5

Printing elements in list1 after removing Element1, Element2
Size of list1: 3
Element3
Element4
Element5

Printing elements in list1 after inserting Element1, Element2
Size of list1: 5
Element3
Element4
Element1
Element5
Element2

Printing elements in list1 after sorting
Element1
Element2
Element3
Element4
Element5

It is recommended to use List<T> generic over ArrayList since it is type-safe, high performance. 

To more refer:https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-5.0#remarks


For my other programming archives -> Go.

If any suggestions please comment about it.

 784 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,488 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.

 720 total views