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; }
}
You don't need to do nothing, the modelbinding will pass null to variable without problems.
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.
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:
string
type is a reference type, therefore it is nullable by default. You can only useNullable<T>
with value types.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
It already has a null value (the null reference):
C# 8.0 is published now so you can make reference types nullable too. For this you have to add
Feature over your namespace. It is detailed here
For example something like this will work:
Also you can have a look this nice article from John Skeet that explains details.