You will learn following:
- Generics in C#
- ArrayList in C#
Generics in C#
In this article, we ae going to explain about Generics in C#. Generic means the general form, not anything specific. In C#, generic means not specific to any particular data type.
The concept of generics is used to create general-purpose classes and method. It is not specific to any particular data type, but type is decided by the compiler at the time of compilation.
Let’s discuss using example, by using a generic “type” parameter T, you can write a single class that can be used by client code without any risk of runtime casts. Example is shown below.
Generic Method Example
public class CustomerList<T>
{
public void Show<T>(T input)
{
Console.WriteLine(input);
}
}
public class Program
{
static void Main(string[] args)
{
// Declare a list of type = int.
CustomerList<int> list1 = new CustomerList<int>();
list1.Show(101);
list1.Show(102);
// Declare a list of type = string.
CustomerList<string> list2 = new CustomerList<string>();
list2.Show("Rakesh");
list2.Show("Mukesh");
Console.Read();
}
}
How can we identify that our class or method is generic. If at the end of class name or method name, you observe angular braces <T> which indicates these are generic and can accept any data type or class in it.
In above example we have created list of type int and string too and both will get printed in console. We can also pass class to our generic method as shown below. Hence, we can say that generic method is generalized and can accept all data types and class too and without any overhead of boxing/ unboxing.
- Class “CustomerList” is generic because it contains <T> after its name.
- Methods “Show” is also generic because of <T> after its name.
- Next we’ll pass new EmpClass into our show methods which is generic.
- In our example it is <T> but it can anything like <P> or anything else.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Generics
{
// Declare the generic class with type T.
public class CustomerList<T>
{
public void Show<T>(T input)
{
Console.WriteLine(input);
}
}
public class Program
{
static void Main(string[] args)
{
// Declare a list of type int.
CustomerList<int> list1 = new CustomerList<int>();
list1.Show(101);
list1.Show(102);
// Declare a list of type string.
CustomerList<string> list2 = new CustomerList<string>();
list2.Show("Rakesh");
list2.Show("Mukesh");
// Declare a list of type EmpClass.
CustomerList<EmpClass> list3 = new CustomerList<EmpClass>();
EmpClass obj = new EmpClass();
obj.CustomerID = 101;
obj.BankNumber = 1;
obj.customerFirstName = "John";
obj.customerLastName = "Smith";
list3.Show(obj);
Console.Read();
}
}
//private void show() { }
public class EmpClass
{
private int _BankNumber, _CustomerID;
private string _customerFirstName, _customerLastName;
public int BankNumber { get { return _BankNumber; } set { _BankNumber = value; } }
public int CustomerID { get { return _CustomerID; } set { _CustomerID = value; } }
public string customerFirstName { get { return _customerFirstName; } set { _customerFirstName = value; } }
public String customerLastName { get { return _customerLastName; } set { _customerLastName = value; } }
}
}
See below, we have passed the "EmpClass" object to our generic "Show" method.
Important points of Generics:
- Generics was introduced in C# 2.0
- Generic allow you to write a class that can work with any data type.
- Generic types are used to maximize code reusability.
- Generics are faster because it does not perform boxing and unboxing.
- Generics are basically used to create collection classes.
- Generics avoid the cost of casting and ensure type safety and also enhance performance.
- Generic data type can be found in”System.Collections.Generic” namespace and one must prefer this instead of “ArrayList”.
- Generic class or methods can be defined using angular brackets <T>, where T is type whose data type is decided at runtime.
Why do we need generics in C#?
As name indicates generics provide us the flexibility to pass any data type or class it. In general, we defined the input parameters either int or string and that method accept int and string only, but with generic make it easy to pass anything as you want. In above example same “Show” method accept int, string and class objects too. We can use generics in method, class, structure and in interface too. Generic allow us to use stronger type-checking and elimination of boxing/ unboxing.
What are the disadvantages of generics in C#?
- Dynamic methods cannot be generic.
- Enumerations cannot have generic type parameters.
- Nested type can never be instantiated.
Do generics increase performance C#?
Yes, in case of generic overhead of casts and boxing/ unboxing do not take place. Additionally, it a common generalize method instead of multiple so there will be a smaller number of lines of code which compiler need to compile so using above point we can say that generics increase performance.
Is generics runtime or compile time?
Regarding type-correctness generics are checked at compile-time. If you ‘ll pass wrong data type, then blue line will appear under your method which indicates compile time error.
When should you use generics?
You can use it to increase your code reusability and enhance the performance. The most common use of generics in C# is to create collection classes.
Do generics exist after compilation?
Yes, same generics stays in the compiled class created by the GIT complier. In IL code generic definition of a class or a method can be seen.
Can we pass null in generic method?
No, it will give error, please check below code. 'Show' is our generic method and we have made a call to this and passed null in it (please check code in highlighted green box).
Can we use generics with array?
No, if we have generic type objects and we want to create its array then it will give compile time error. Hence it is not feasible.
What are the benefits of generics in C#?
- It provides code reusability.
- There is no need for casting. This overhead can be saved.
- It is faster.
- No boxing and unboxing happen in generics.
- We can create generic for interface, classes, method, events and delegate too.
How to use generic class in C#?
Please check out below sample code.
// Below is generic class and generic method
public class CustomerList<T>
{
public void Show<T>(T input)
{
Console.WriteLine(input);
}
}
// Going to use above generic method in below code.
CustomerList<int> list1 = new CustomerList<int>();
list1.Show(101);
list1.Show(102);
We hope above explanation of generic have cleared your doubts regarding use of generics and I believe you’ll use generic in your daily development practices. For more information you can check out Microsoft learn.
For more information you can visit our C# Section for more such articles.
ArrayList in C#
ArrayList is a powerful feature of the C# language. This is a non-generic collection type defined in the System. Collections namespace. Used to create dynamic arrays. This means that the size of the array will automatically grow or shrink depending on your program's needs. There is no need to specify the size of the ArrayList. In other words, an ArrayList represents an ordered collection of objects that can be indexed individually. An ArrayList can contain elements of the same type and elements of different types.
This belongs to a non-generic collection.
important Points of ArrayList:
- The ArrayList class implements the IEnumerable, ICollection, IList, and ICloneable interfaces.
- The ArrayList class inherits the Object class.
- The ArrayList is defined under System.Collections namespace. So, when you use Arraylist in your program you must add System.Collections namespace.
- You cannot implement a multi-dimensional array using ArrayList.
- The capacity of an ArrayList is the number of elements the ArrayList can hold.
- You are allowed to use duplicate elements in your ArrayList.
- You can apply searching and sorting on the elements present in the ArrayList.
- Arraylist can accept null as a valid value.
How to create the ArrayList?
ArrayList class has three constructors which are given below:
- ArrayList(): This constructor is used to create an instance of the ArrayList class that is empty and has no initial capacity.
- ArrayList(Int32): This constructor is used to create an instance of the ArrayList class with an empty and specified initial capacity.
- ArrayList(ICollection): This constructor is used to create an array list that is initialized with the elements of the specified collection and has the same initial capacity as copied from the collection.
using System.Collections;
ArrayList list_name = new ArrayList();
In below program let's check how to create an ArrayList, adding elements to the ArrayList, and how to access the elements of the ArrayList.
using System;
using System.Collections;
class CodeConfig {
static public void Main()
{
ArrayList arr = new ArrayList();
arr.Add(10.56);
arr.Add("CodeConfig.in");
arr.Add(code);
arr.Add('India');
arr.Add(101);
// Now Accessing the elements
foreach(var elements in arr)
{
Console.WriteLine(elements);
}
}
}
How to find the Capacity and Count of elements of the ArrayList?
using System;
using System.Collections;
class CodeConfig{
public static void Main() {
// Creating an ArrayList and adding element to it.
ArrayList myLst = new ArrayList();
myLst.Add(101);
myLst.Add(102);
myLst.Add(103);
myLst.Add(104);
myLst.Add(105);
// Displaying count of elements within ArrayList
Console.WriteLine("Number of elements: " + myLst.Count);
// Displaying Current capacity of ArrayList
Console.WriteLine("Current capacity: " + myLst.Capacity);
}
}
How to remove elements from the ArrayList?
ArrayList provides 4 different methods to remove elements and the methods are as given below:
- Remove: This method is used to remove the first occurrence of a specific object from the ArrayList.
- RemoveAt: This method is used to remove the element at the specified index of the ArrayList.
- RemoveRange: This method is used to remove a range of elements from the ArrayList.
- Clear: This method is used to remove all the elements from the ArrayList.
using System;
using System.Collections;
class CodeConfig
{
public static void Main() {
// Creating an ArrayList and adding element to it.
ArrayList myLst = new ArrayList();
myLst.Add(101);
myLst.Add(102);
myLst.Add(103);
myLst.Add(104);
myLst.Add(105);
myLst.Remove('102'); // Remove the '102' element.
myLst.RemoveAt(3); // Remove the element present at index 3
myLst.RemoveRange(1, 3); // Remove 3 elements starting from index 1
myLst.Clear(); // Remove all the elements present in ArrayList.
}
}
How to sort the elements of the ArrayList?
ArrayList allows you to sort the elements present in a given ArrayList using the Sort() method. This method sorts the ArrayList using the QuickSort algorithm, placing the elements in ascending order. The following example shows how to use this method.
using System;
using System.Collections;
class CodeConfig
{
public static void Main() {
// Creating an ArrayList and adding element to it.
ArrayList myLst = new ArrayList();
myLst.Add(101);
myLst.Add(104);
myLst.Add(105);
myLst.Add(102);
myLst.Add(103);
// ArrayList before sorting
foreach(var elements in myLst)
{
Console.WriteLine(elements);
}
// Using sort() method
myLst.Sort();
// ArrayList after sorting
foreach(var elements in myLst)
{
Console.WriteLine(elements);
}
}
}
In this article we tried to explain ArrayList in C# with Examples. I hope you enjoyed reading this article. For more information you can check out Microsoft learn.
For more information you can visit our C# Section for more such articles.
No comments:
Post a Comment