How can I make my string property nullable?

asp.net-mvc c# ef-migrations entity-framework

Question

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; }
}   
1
52
2/19/2019 9:51:24 AM

Accepted Answer

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.

119
9/29/2015 8:56:25 PM

Popular Answer

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow