1

I want to write a nullable string to file using BinaryWriter and this code:

  BinaryWriter writer = new BinaryWriter(st);
  String? s;
  if(s!=null){
        writer.Write(s);
    }

but this error occurs:

The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'

How can I solve this problem?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Majid
  • 13,853
  • 15
  • 77
  • 113

4 Answers4

4

Strings can always be null, you don't need to try and make it nullable as they're not value types. Just remove the ? That makes it nullable to fix it.

Ian
  • 33,605
  • 26
  • 118
  • 198
2

Strings are already nullable in C#.NET, they're a reference type with syntactic sugar around them to make them easier to use. You can't make a nullable double nullable, the universe would collapse.

Jeff Watkins
  • 6,343
  • 16
  • 19
2

According to MSDN documentation, we can see that Nullable type can be used only with structs:

[SerializableAttribute]
public struct Nullable<T>
where T : struct

p.s. see also Constraints on Type Parameters.

Dzmitry Martavoi
  • 6,867
  • 6
  • 38
  • 59
1

String is a reference type. It can not be nullable.
public struct Nullable<T> where T : struct, new()

Vladimir
  • 7,345
  • 4
  • 34
  • 39