When to use <> instead of ()

When we are suppose to use different parentheses in C#. When I run into a situation where i am trying to tell if i need to put <> or ().

The dumbed down version to explain is this;

() are for variables. <> are for types. If you have both, <> always comes first.

You would never has A(int). It would be A<int>. You’d also never have B<5>. It would always be B(5). And, rule two, you might have C<int>(5), but never C(5)<int>.

<> are used in generics.

Generics in C#

Generic is a type used to define a class, structure, interface, or method with placeholders to indicate that they can store or use one or more of the types. In C#, the compiler will replace placeholders with the specified type at compile time. We use generic frequently with collections.

Generics are useful for improving code reusability, type safety, and performance compared with non-generic types e.g. arraylist.

Here is a code sample;

//Generic example - using single generic type
public class Hospital<T>            //Here <T> is a a placeholder beside Hospital class
{
    private T Cases;                //Declared a variable named "Cases" of type T
    public Hospital(T value)        //Constructor take another variable named value
    {
        this.Cases = value;         //assinged received type to containting type "Cases"
    }

    public void Show()
    {
        Console.WriteLine(this.Cases);
    }
}

Let’s implement this in our .NET6 main class;

Console.WriteLine("Hello, World!");

//use Hospital class
Hospital<int> x = new Hospital<int>(100);       //replacing T with int
Hospital<string> y = new Hospital<string>("Hospital Cases");
x.Show();
y.Show();

We can use two generic types in a class;

//using two generic types
public class EliteHospital<T, U>            //Here <T> is a a placeholder beside Hospital class
{
    // PatientCount of type T
    public T? PatientCount {  get; set; }

    //Docotrs of U
    public U? Doctors { get; set; }  
}

This is how we can use this;

Console.WriteLine("Hello, World!");
//using EliteHospital class
EliteHospital<int, string> xx = new EliteHospital<int, string>();
xx.PatientCount = 100;
xx.Doctors = "Available";
Console.WriteLine(xx.PatientCount);
Console.WriteLine(xx.Doctors);

Console.WriteLine("Press any key to continue..");
Console.ReadKey();