How to make value types without null in C #?

For instance:

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

int?works fine, but I can't make the speaker null. It turned out to be surprisingly difficult for Google, I thought it would be easy ...

+3
source share
4 answers

Why do you need this? Obscene types (i.e. Link types) can already be set and mapped to null.

Adding a wrapper Nullable<T>over objects of a reference type would create two levels of zeroing; meaningless complexity, so it is not allowed.

+13
source

It's simple. The non-value types are actually called .NET link types and are automatically nullified. Just change your code:

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

Wild swag:

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

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

A lot of fish is already here, but if you want to learn how to fish, I suggest taking a look at the Jon Skeet book C # in depth . Chapters 4.1-4.5 discuss all aspects of the "concept of invalidity" in C #.

0
source

Source: https://habr.com/ru/post/1775655/


All Articles