ASPCode.net logo
  • Home 
  • Blogs 
  • Tags 
Blog
  1. Home
  2. Articles
  3. C# Advanced - Generics

C# Advanced - Generics

Posted on July 4, 2024  (Last modified on October 11, 2024) • 2 min read • 292 words
C#
 
C#
 
Share via
ASPCode.net
Link copied to clipboard

Video is in Swedish

Generics in C# are a feature that allows you to create classes, interfaces and methods that can work with any data type. This is achieved by using placeholders called type parameters which represent the actual types of the data at runtime.

Generics provide several benefits such as improved code reusability, better performance due to compile-time checks, and increased safety through type checking. They also make your code more readable and maintainable since you can write generic code that works with any type without having to repeat yourself for each specific type.

To use generics in C#, you need to define a class or method with one or more type parameters enclosed in angle brackets < >. For example, consider the following code:

public class Container<T>
{
    private T _item;

    public void SetItem(T item)
    {
        _item = item;
    }

    public T GetItem()
    {
        return _item;
    }
}

In this example, T is a type parameter that represents the actual data type of the _item field and the SetItem and GetItem methods. You can use this class to store any type of data by specifying the desired type when creating an instance of the Container class.

// Create a container for integers
var intContainer = new Container<int>();
intContainer.SetItem(42);
Console.WriteLine(intContainer.GetItem()); // Output: 42

// Create a container for strings
var stringContainer = new Container<string>();
stringContainer.SetItem("Hello, World!");
Console.WriteLine(stringContainer.GetItem()); // Output: Hello, World!

Generics are a powerful feature in C# that can help you write more efficient and maintainable code. By using type parameters, you can create classes, interfaces, and methods that work with any data type without having to repeat yourself for each specific type. This makes your code more readable and easier to maintain while also providing improved performance and safety through compile-time checks.

Video  

Swedish

 C# Advanced - Git Bash CLI
C# Advanced - Delegates 
Follow me

I code in Java, C#, Golang, SQL and more

     
© 2024 Systementor AB
ASPCode.net
Code copied to clipboard