I have a simple struct that has limited use. The struct is created in a method that calls the data from the database. If there is no data returned from the database I want to be able to return a null, but Visual Studio complains, Cannot convert null to PackageName.StructName because it is a non-nullable value type.
How can I make it nullable?
You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type.
Nullable variables may either contain a valid value or they may not — in the latter case they are considered to be nil . Non-nullable variables must always contain a value and cannot be nil . In Oxygene (as in C# and Java), the default nullability of a variable is determined by its type.
You want to look into the Nullable<T>
value type.
public struct Something
{
//...
}
public static Something GetSomethingSomehow()
{
Something? data = MaybeGetSomethingFrom(theDatabase);
bool questionMarkMeansNullable = (data == null);
return data ?? Something.DefaultValue;
}
The definition for a Nullable<T>
struct is:
struct Nullable<T>
{
public bool HasValue;
public T Value;
}
It is created in this manner:
Nullable<PackageName.StructName> nullableStruct = new Nullable<PackageName.StructName>(params);
You can shortcut this mess by simply typing:
PackageName.StructName? nullableStruct = new PackageName.StructName(params);
See: MSDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With