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?

3
  • 2
    you should take a look at brandonscript answer on this question it explains alot. Commented Mar 14, 2018 at 18:23
  • should this question get closed? Commented Mar 14, 2018 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 Commented Mar 14, 2018 at 18:34

2 Answers 2

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

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

Comments

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.

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.