70
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;
Xaqron
  • 29,931
  • 42
  • 140
  • 205
  • 13
    Make it a class? – Shurdoof Dec 20 '10 at 16:55
  • 3
    I was thinking with just two members, it would be a funny class I was ashamed someone look into my code :) – Xaqron Dec 20 '10 at 17:03
  • 1
    A mutable structure is much more problematic than a class with only two members. – Dan Bryant Dec 20 '10 at 17:39
  • 2
    Side comment: any reason on using `String` instead of `string`? – danielrozo Feb 06 '14 at 13:02
  • 2
    The answers that say "make it a class," while fundamentally correct, don't account for the case where you are using a third party library that contains a struct type. In some cases, you may want a data member of that type that can be uninitialized or unset, and there's no obvious default value that works. Edit: Which ziplin's solution below DOES address. – Tim Keating Apr 28 '15 at 20:34

3 Answers3

74

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.

Community
  • 1
  • 1
kemiller2002
  • 113,795
  • 27
  • 197
  • 251
55

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

AccountInfo? myAccount = null;
Dlongnecker
  • 3,008
  • 3
  • 25
  • 40
23

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".

Greg Beech
  • 133,383
  • 43
  • 204
  • 250