How can I make my string property nullable?
Solution 1:
String is a reference type and always nullable, you don't need to do anything special. Specifying that a type is nullable is necessary only for value types.
Solution 2:
C# 8.0 is published now so you can make reference types nullable too. For this you have to add
#nullable enable
Feature over your namespace. It is detailed here
For example something like this will work:
#nullable enable
namespace TestCSharpEight
{
public class Developer
{
public string FullName { get; set; }
public string UserName { get; set; }
public Developer(string fullName)
{
FullName = fullName;
UserName = null;
}
}}
Also you can have a look this nice article from John Skeet that explains details.
Solution 3:
System.String is a reference type so you don't need to do anything like
Nullable<string>
It already has a null value (the null reference):
string x = null; // No problems here
Solution 4:
Strings are nullable in C# anyway because they are reference types. You can just use public string CMName { get; set; }
and you'll be able to set it to null.
Solution 5:
It's been a while when the question has been asked and C# changed not much but became a bit better. Take a look Nullable reference types (C# reference)
string notNull = "Hello";
string? nullable = default;
notNull = nullable!; // null forgiveness
C# as a language a "bit" outdated from modern languages and became misleading.
for instance in typescript
, swift
there's a "?" to clearly say it's a nullable type, be careful. It's pretty clear and it's awesome. C# doesn't/didn't have this ability, as a result, a simple contract IPerson very misleading. As per C# FirstName and LastName could be null but is it true? is per business logic FirstName/LastName really could be null? the answer is we don't know because C# doesn't have the ability to say it directly.
interface IPerson
{
public string FirstName;
public string LastName;
}