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;
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.
When you declare it, declare it with a "?" if you prefer
AccountInfo? myAccount = null;