How to make a 'struct' Nullable by definition?

Xaqron picture Xaqron · Dec 20, 2010 · Viewed 54.3k times · Source
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;

Answer

kemiller2002 picture kemiller2002 · Dec 20, 2010

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.