Alex Rivera | Logout

C# struct, how to assign a null value?

Asked 2010-11-10T20:36:18.987
41

I have a list:

List<int, SomeStruct>

For some reason, it is not allowing me to assign null values to it. What do I do if I want to have no struct associated?

Edit
Report

2 Answers

66

Use nullable types:

List<int, SomeStruct?>

You can't assign null to an element of the list because structs are value types, while null means an empty pointer, and so can only be assigned to reference type variables.

Also note that List as you're using it doesn't exist in .NET! Perhaps you want Dictionary?

answered 2010-11-10T20:37:17.090
6

Unless you have defined a custom generic collection, List<T, U> doesn't exist in the System.Collections.Generic namespace. Did you rather mean Dictionary<TKey, TValue>?

You can use Nullable types: Using Nullable Types (C# Programming Guide).

As for any ValueType, you need to specify explicitly that you will allow null values for your type. You can do so by concatenating the '?' character with your type name, or by marking it as Nullable, where T is the name of your structure.

answered 2010-11-10T20:48:25.853

Your Answer