22
votes

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?

7

7 Answers

22
votes

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

13
votes
public struct Something
{
    //...
}

public static Something GetSomethingSomehow()
{
    Something? data = MaybeGetSomethingFrom(theDatabase);
    bool questionMarkMeansNullable = (data == null);
    return data ?? Something.DefaultValue;
}
7
votes

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

4
votes

Nullable<T> is a wrapper class that creates a nullable version of the type T. You can also use the syntax T? (e.g. int?) to represent the nullable version of type T.

2
votes

Use the built-in shortcuts for the Nullable<T> struct, by simply adding ? to the declaration:

int? x = null;

if (x == null) { ... }

Just the same for any other type, struct, etc.

MyStruct? myNullableStruct = new MyStruct(params);
1
votes

You could make something nullable for example like this:

// Create the nullable object.
int? value = new int?();

// Check for if the object is null.
if(value == null)
{
    // Your code goes here.
}
0
votes

You can use default as an alternative

public struct VelocityRange
{
    private double myLowerVelocityLimit;
    private double myUpperVelocityLimit;
}

VelocityRange velocityRange = default(VelocityRange);