Reputation: 31795
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?
Upvotes: 26
Views: 68617
Reputation: 9
You can use default as an alternative
public struct VelocityRange
{
private double myLowerVelocityLimit;
private double myUpperVelocityLimit;
}
VelocityRange velocityRange = default(VelocityRange);
Upvotes: 0
Reputation: 17617
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);
Upvotes: 3
Reputation: 181
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.
}
Upvotes: 1
Reputation: 19543
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.
Upvotes: 4
Reputation: 71935
public struct Something
{
//...
}
public static Something GetSomethingSomehow()
{
Something? data = MaybeGetSomethingFrom(theDatabase);
bool questionMarkMeansNullable = (data == null);
return data ?? Something.DefaultValue;
}
Upvotes: 13
Reputation: 63445
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
Upvotes: 8