Why `where T: class`

I am reading a book on c# 12. In this example the author includes where T: class but why is that needed? It seems to work fine without
No description
5 Replies
Jason_Bjorn
Jason_Bjorn7d ago
class Program
{
public static T GetLast<T>(T[] items) => items[^1];

public static T[] GetNonNullItems<T>(T[] items)
=> Array.FindAll(items, value => value != null);

public static void PrintArray<T>(T[] array)
{
Console.Write("[ ");
foreach (var e in array)
{
Console.Write($"{e} ");
}

Console.WriteLine("]");
}


public static void Main()
{
int[] values = [1, 2, 3];
int?[] values2 = [1, null, 3];

string[] words = ["Hello", "World"];
string?[] words2 = ["Howdy", null, "Partner"];

PrintArray(GetNonNullItems(values));
PrintArray(GetNonNullItems(values2));
PrintArray(GetNonNullItems(words));
PrintArray(GetNonNullItems(words2));
}
}
class Program
{
public static T GetLast<T>(T[] items) => items[^1];

public static T[] GetNonNullItems<T>(T[] items)
=> Array.FindAll(items, value => value != null);

public static void PrintArray<T>(T[] array)
{
Console.Write("[ ");
foreach (var e in array)
{
Console.Write($"{e} ");
}

Console.WriteLine("]");
}


public static void Main()
{
int[] values = [1, 2, 3];
int?[] values2 = [1, null, 3];

string[] words = ["Hello", "World"];
string?[] words2 = ["Howdy", null, "Partner"];

PrintArray(GetNonNullItems(values));
PrintArray(GetNonNullItems(values2));
PrintArray(GetNonNullItems(words));
PrintArray(GetNonNullItems(words2));
}
}
Angius
Angius7d ago
To not accept structs
Pobiega
Pobiega7d ago
generics are a bit finnicky with how they deal with null. Im sure you are aware that a struct can't be null, so a bool? can't actually be null, its instead handled by a wrapper called Nullable<T> you can look up exactly how it works, but due to structs not being able to be null, there are generic constraints like class, struct, notnull and class? https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters for more info
Jason_Bjorn
Jason_Bjorn7d ago
thank you @ZZZZZZZZZZZZZZZZZZZZZZZZZ @Pobiega
arion
arion7d ago
Because they already rejected structnt as a constraint name