0

for my Unity game I created a JSON file that holds the speedrun times. The saved times are Timespan strings. When loading the data I parse the strings to Timespan values. When saving the time I save the Timespan as a string to the file.

Example level in the JSON file:

{
  "id": 1,
  "personalBest": "00:00:00.0001336",
  "perfectTime": "00:00:00.0001335",
}

If a level is not passed yet I want the personalBest property having the value null instead of something like this

00:00:00.0000000

or

99:99:99.9999999

In my serializable class I currently have this code

[Serializable]
public class Level
{
    public int id;
    public string? personalBest; // this value could be null
    public string perfectTime;
}

But I get this error

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

Is a workaround possible?

Question3r
  • 2,166
  • 19
  • 100
  • 200
  • 2
    you should take a look at brandonscript answer on [this question](https://stackoverflow.com/a/21121267/2748412) it explains alot. – Franck Mar 14 '18 at 18:23
  • should this question get closed? – Question3r Mar 14 '18 at 18:25
  • yes, it is a duplicate. As a note, you should maybe rethink the way you save things, you can avoid having this saved as null by making `personalBest` getting the value from an external list containing the id and time – Franck Mar 14 '18 at 18:34

2 Answers2

2

So in C# string is already a nullable type. You should be fine just using a normal string in place of string?. This means you can just set it to null by doing the following:

string myString = null;

If I'm completely misunderstanding your question, please let me know.

For saving null in JSON, check here

Daxtron2
  • 1,239
  • 1
  • 11
  • 19
1

An important thing to understand regarding the string type is this:

string is a reference type, thus nullable, and when a string field is declared but not initialized it will have its value set to "" and not null.

I.e.:

public string myString;
if (myString != null) {
    Debug.Log("String is not null");
}

will print String is not null in the console.

This is what throws some people off, since usually reference types when declared but not yet initialized have their value set to null by default.

However, if you declare the variable with an autoproperty instead of a field, then it will behave as any other reference type, i.e. null by default.

public string myString {get;set;}
if (myString == null) {
    Debug.Log("String is null");
}

will print String is null in the console.

Galandil
  • 4,169
  • 1
  • 13
  • 24