I want to make the Middle Name (CMName
) 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; } }
In this topic, we are going to learn about C# Nullable String. To assign null to a value type, we need to use Nullable<T> struct. The nullable type can only be used with value types and not with reference types. So, we cannot use nullable with string.
You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
There are two ways to control the nullable context. At the project level, you can add the <Nullable>enable</Nullable> project setting. In a single C# source file, you can add the #nullable enable pragma to enable the nullable context. See the article on setting a nullable strategy.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With