3

For example:

public class Stereo {
   public Speaker? LeftSpeaker;
   public int? Volume;
}

The int? works fine, but I'm unable to make Speaker nullable. This is turning out to be surprisingly hard to Google, I thought this would be simple ...

4 Answers 4

13

Why would you want that? Non-value types (i.e. reference types) can already be set and compared to null.

Adding a Nullable<T> wrapper over reference-type objects would create two layers of nullability; pointless complexity, hence it is not allowed.

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

2 Comments

Half tempted to retag this question duh.
Well this could be why Googling "make reference types nullable" wasn't turning up anything. Thanks!
2

It is simple. "non-value" types are actually called references types in .NET and are automatically nullable. Just change your code thusly:

public class Stereo {
   public Speaker LeftSpeaker; // ? removed for ref type
   public int? Volume;
}

Comments

0

Wild swag:

public class Stereo { 
   public Speaker LeftSpeaker; 
   public int? Volume; 

   public Stereo() {
       LeftSpeaker = null;   // Mission accomplished.
   }
} 

4 Comments

@Noldorin: woops. missed some () didn't I?
Yeah, just though I'd fix it for you, since it was an obvious typo. :)
@Noldorin: No sweat. I've been mass-producing properties in dummy classes for the last couple of days, so my brain is just glossy :)
Yep, that would a cause! Easy mistake to make anyway, outside of a code editor.
0

A lot of fish already here - but if you want to learn how to fish, I suggest having a look into Jon Skeet's book C# in Depth. Chapters 4.1 to 4.5 are dealing with all facets of the "concept of nullity" in C#.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.