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
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.
string is by default Nullable ,you don't need to do anything to make string Nullable
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;
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 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.