How can I make my string property nullable?
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;
}
}}
If you want to globally set nullable property for whole project; you can do it in .csproj file by adding
<Nullable>enable</Nullable>
property to PropertyGroup. It will enable nullablity for all classes in the project.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
</PropertyGroup>
<!-- Other Settings -->
</Project>
Also you can have a look this nice article from John Skeet that explains details.
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
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.
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.