views:

1971

answers:

5

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?

+11  A: 

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

Andrew Hare
+6  A: 
public struct Something
{
    //...
}

public static Something GetSomethingSomehow()
{
    Something? data = MaybeGetSomethingFrom(theDatabase);
    bool questionMarkMeansNullable = (data == null);
    return data ?? Something.DefaultValue;
}
mquander
As far as I understand, this code does not return null as Malfist wants to.
Luis Filipe
IIRC, it was intended as an illustration of the use of nullable types, since the poster didn't seem to understand exactly what they were.
mquander
+1  A: 

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.

Orion Adrian
+1  A: 

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

John Rasch
A: 

For using System.Nullable please refer Nullable type in C# brief details

bimbim.in