Search code examples
c#nullablebinarywriternon-nullable

Writing Nullable value with BinaryWriter


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?


Solution

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