C
C#9mo ago
rcnespoli

List extension

I created this extesion
public static class ListUtilExtension
{
public static void AddOptional<T>(this List<T> list, T? item)
{
if (item is null)
{
return;
}
list.Add(item);
}
}
public static class ListUtilExtension
{
public static void AddOptional<T>(this List<T> list, T? item)
{
if (item is null)
{
return;
}
list.Add(item);
}
}
In my test, to string worked
[Fact]
[Description("Should not add null value in list")]
public void ShouldNotAddNullValue()
{
// Setup
var list = new List<string>();

// Exercise
list.AddOptional(null);

// Verify
Assert.Empty(list);
}
[Fact]
[Description("Should not add null value in list")]
public void ShouldNotAddNullValue()
{
// Setup
var list = new List<string>();

// Exercise
list.AddOptional(null);

// Verify
Assert.Empty(list);
}
But when I try with int, not worked
[Fact]
[Description("Should add value after tried to add null value in list")]
public void ShouldAddValueAfterTryAddNullValue()
{
// Setup
const int expectedCountInList = 2;
var list = new List<int>();
var firstIntToAdd = Random.Shared.Next(1, int.MaxValue);
var secondIntToAdd = Random.Shared.Next(1, int.MaxValue);
list.AddOptional(firstIntToAdd);
list.AddOptional(null);

// Exercise
list.AddOptional(secondIntToAdd);

// Verify
Assert.Equal(expectedCountInList, list.Count);
}
[Fact]
[Description("Should add value after tried to add null value in list")]
public void ShouldAddValueAfterTryAddNullValue()
{
// Setup
const int expectedCountInList = 2;
var list = new List<int>();
var firstIntToAdd = Random.Shared.Next(1, int.MaxValue);
var secondIntToAdd = Random.Shared.Next(1, int.MaxValue);
list.AddOptional(firstIntToAdd);
list.AddOptional(null);

// Exercise
list.AddOptional(secondIntToAdd);

// Verify
Assert.Equal(expectedCountInList, list.Count);
}
Show to me: Argument type 'null' is not assignable to parameter type 'int' What I did wrong?
2 Replies
reflectronic
reflectronic9mo ago
T? on a generic method, by default, does not let you pass null for structs you need to write two generic methods
public static void Add<T>(this List<T>, T? item) where T : class { … }

public static void Add<T>(this List<T>, T? item) where T : struct { … }
public static void Add<T>(this List<T>, T? item) where T : class { … }

public static void Add<T>(this List<T>, T? item) where T : struct { … }
the code can be identical for both in this case the where T : struct one will use the special Nullable<T> type that allows you to pass null
rcnespoli
rcnespoliOP9mo ago
oh nice! Is there some doc to I see more details about generics? Thank you
Want results from more Discord servers?
Add your server