1

I am trying to do this:

protected List<T> list = new List<T>(); for (int i = 0; i < size; i++) { list.Add(null); } 

I get a compiler error saying "cannot convert from null to T".

I have looked around but could not find an answer to this question.

3
  • What is T in this context? Commented Feb 15, 2021 at 18:44
  • 1
    @David I spent a while trying to figure this out, T is a reference type and once I added where T : class to the constraints I was able to add the null member. Avoidable question, but maybe someone else runs into this problem and can benefit from this. Commented Feb 15, 2021 at 18:46
  • list = Enumerable.Repeat(default(T), size).ToList(); note, that if T is struct (e.g. int, bool etc.), default(T) will not be null Commented Feb 15, 2021 at 19:00

1 Answer 1

0

Okay, I'm sorry, literally a few seconds after posting this I noticed I didnt put a constraint into the class header and when including where T : class in the constraints, I can null the list member.

Sign up to request clarification or add additional context in comments.

5 Comments

Or you can use default(T)
@Dennis_E that's actually a great one
@Dennis_E I would say you should post thus as an answer.
@Dmitry Bychenko (initial quesiton comments) correctly stated, that default(T) will not equate to null when dealing with structs like int, bool, etc
If the goal is to specifically add null to the list, default(T), in and of itself, does not guarantee so, therefore it wouldn't be a good answer to this post.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.