[c#] How can I make my string property nullable?

I want to make the Middle Name of person optional. I have been using C#.net code first approach. For integer data type its easy just by using ? operator to make in nullable. I am looking for a way to make my sting variable nullable. I tried to search but could not find the way to make it nullable.

Below is my code. Please suggest me how to make it nullable.

public class ChildrenInfo
{
    [Key]
    public int ChidrenID { get; set; }

    [Required]
    [Display(Name ="First Name")]
    [StringLength(50,ErrorMessage ="First Name cannot exceed more than 50 characters")]
    [RegularExpression(@"^[A-Z]+[a-z]*$",ErrorMessage ="Name cannot have special character,numbers or space")]
    [Column("FName")]
    public string CFName { get; set; }

    [Display(Name ="Middle Name")]
    [RegularExpression(@"^[A-Z]+[a-z]*$",ErrorMessage ="Middle Name cannot have special character,numbers or space")]
    [StringLength(35,ErrorMessage ="Middle Name cannot have more than 35 characters")]
    [Column("MName")]
    public string? CMName { get; set; }
}   

The answer is


string type is a reference type, therefore it is nullable by default. You can only use Nullable<T> with value types.

public struct Nullable<T> where T : struct

Which means that whatever type is replaced for the generic parameter, it must be a value type.


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

string is by default Nullable ,you don't need to do anything to make string Nullable


As others have pointed out, string is always nullable in C#. I suspect you are asking the question because you are not able to leave the middle name as null or blank? I suspect the problem is with your validation attributes, most likely the RegEx. I'm not able to fully parse RegEx in my head but I think your RegEx insists on the first character being present. I could be wrong - RegEx is hard. In any case, try commenting out your validation attributes and see if it works, then add them back in one at a time.


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.


It's not possible to make reference types Nullable. Only value types can be used in a Nullable structure. Appending a question mark to a value type name makes it nullable. These two lines are the same:

int? a = null;
Nullable<int> a = null;

You don't need to do anything, the Model Binding will pass null to property without any problem.


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.


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;
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to entity-framework

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF

Examples related to entity-framework-migrations

EF Core add-migration Build Failed How can I make my string property nullable? There is already an object named in the database Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration EF 5 Enable-Migrations : No context type was found in the assembly How to delete and recreate from scratch an existing EF Code First database Generate full SQL script from EF 5 Code First Migrations Entity Framework Migrations renaming tables and columns EF Migrations: Rollback last applied migration? Reset Entity-Framework Migrations