71
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; 
5
  • 13
    Make it a class? Commented Dec 20, 2010 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 :) Commented Dec 20, 2010 at 17:03
  • 1
    A mutable structure is much more problematic than a class with only two members. Commented Dec 20, 2010 at 17:39
  • 2
    Side comment: any reason on using String instead of string? Commented Feb 6, 2014 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. Commented Apr 28, 2015 at 20:34

3 Answers 3

75

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.

Sign up to request clarification or add additional context in comments.

Comments

58

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

AccountInfo? myAccount = null; 

2 Comments

That's not "defining" it. That's declaring it.
Adding ? after my variable dec at the top of my file worked for me, let it be null. I personally like structs when I need collections of datasets, especially for unity where dictionaries dont show up in the inspector. Thanks for answering the question and not just saying "Lul you are doing it wrong go learn harder"
24

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.