Xaqron
Xaqron

Reputation: 30857

How to make a 'struct' Nullable by definition?

struct AccountInfo
{
   String Username;
   String Password;
}

now if I want to have a Nullable instance I should write:

Nullable<AccountInfo> myAccount = null;

But I want make the struct Nullable by nature and it can be used like this (without use of Nullable<T>):

AccountInfo myAccount = null;

Upvotes: 71

Views: 83086

Answers (3)

Dlongnecker
Dlongnecker

Reputation: 3047

When you declare it, declare it with a "?" if you prefer

AccountInfo? myAccount = null;

Upvotes: 58

kemiller2002
kemiller2002

Reputation: 115498

You can't. Struct are considered value types, and by definition can't be null. The easiest way to make it nullable is to make it a reference type.

The answer you need to ask yourself is "Why is this a struct?" and unless you can think of a really solid reason, don't, and make it a class. The argument about a struct being "faster", is really overblown, as structs aren't necessarily created on the stack (you shouldn't rely on this), and speed "gained" varies on a case by case basis.

See the post by Eric Lippert on the class vs. struct debate and speed.

Upvotes: 75

Greg Beech
Greg Beech

Reputation: 136667

The short answer: Make it a class.

The long answer: This structure is mutable which structs should never be, doesn't represent a single value which structs always should, and has no sensible 'zero' value which structs also always should, so it probably shouldn't be a value type. Making it a class (reference type) means that it is always possible for it to be null.


Note: Use of words such as "never" and "always" should be taken with an implied "almost".

Upvotes: 24

Related Questions