Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a Non-nullable value type nullable

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?

like image 323
Malfist Avatar asked Feb 27 '09 18:02

Malfist


People also ask

How do you make a type 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.

Can we create nullable type based on reference type?

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.

Is a non-nullable value 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.


3 Answers

You want to look into the Nullable<T> value type.

like image 67
Andrew Hare Avatar answered Oct 23 '22 14:10

Andrew Hare


public struct Something
{
    //...
}

public static Something GetSomethingSomehow()
{
    Something? data = MaybeGetSomethingFrom(theDatabase);
    bool questionMarkMeansNullable = (data == null);
    return data ?? Something.DefaultValue;
}
like image 37
mqp Avatar answered Oct 23 '22 14:10

mqp


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

like image 8
John Rasch Avatar answered Oct 23 '22 13:10

John Rasch