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?
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?
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
?
SomeStruct?
is syntactic sugar for Nullable<SomeStruct>
. You can't access members directly, but that's the price you pay for using null
semantics with a value type. –
Thankless In C# a struct is a 'value type', which can't be null.
If you really, really need to be able to null this, then make it into a 'nullable' type by adding a trailing question mark.
You should probably look into the details of this more first, though - it's quite likely you don't really want a 'struct' at all, but would be better with a 'class'.
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.
All of the existing answers here are correct: in C# struct is a value type
and cannot be null
.
However some struct implementations (but definitely not all) follow a convention where the default/empty value is stored in a Empty
static field. Sometimes there is also an IsEmpty
property:
// System.Guid
public struct Guid : IFormattable, IComparable, IComparable<Guid>, IEquatable<Guid>
{
public static readonly Guid Empty;
...
}
// System.Drawing.Point
public struct Point
{
public static readonly Point Empty;
public bool IsEmpty { get; }
...
}
If the struct has an Empty
field or IsEmpty
property, then you can use it to test if the struct variable is Empty
instead of null
. Otherwise use a nullable wrapper as the other answers state.
If you are the programmer of the struct, strongly consider adding an Empty
field and IsEmpty
property if appropriate.
© 2022 - 2024 — McMap. All rights reserved.