Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - list to store nullable types

Tags:

c#

list

In C# we can declare a list to store int, like

List myList = new List {1,1,2};

I want to store null values as well (nullable type) hence I want to create a list of nullable types. Something like this

        List<?int> myList = new List<int> {1,1,2};

Above code does not compile. Does .Net supports list of nullable types?

Atul Sureka

like image 916
Atul Sureka Avatar asked Mar 19 '26 19:03

Atul Sureka


1 Answers

Sure, you need

List<int?> myList = new List<int?> {1,1,2};
  1. It's int? not ?int
  2. You need the nullable int when you construct it as well as in the variable definition.

As a side note, you can't actually declare a list like List myList = new List {1, 1, 2}; as there's no non-generic List.

like image 73
Ray Avatar answered Mar 21 '26 08:03

Ray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!