Introduction to C# Nullable String. In C#, there exist two types of variables which are value types and reference types. Value type variables cannot be assigned null, whereas we can assign null to reference type variables. As the string is a reference type, it can be null.
The only way to create a non-nullable type is to declare a struct - structs, however, cannot inherit or be inherited from.
In C# 8.0, strings are known as a nullable “string!”, and so the AllowNull annotation allows setting it to null, even though the string that we return isn't null (for example, we do a comparison check and set it to a default value if null.)
Nullable variables may either contain a valid value or they may not — in the latter case they are considered to be nil . Non-nullable variables must always contain a value and cannot be nil . In Oxygene (as in C# and Java), the default nullability of a variable is determined by its type.
Use string
instead of string?
in all places in your code.
The Nullable<T>
type requires that T is a non-nullable value type, for example int
or DateTime
. Reference types like string
can already be null. There would be no point in allowing things like Nullable<string>
so it is disallowed.
Also if you are using C# 3.0 or later you can simplify your code by using auto-implemented properties:
public class WordAndMeaning
{
public string Word { get; set; }
public string Meaning { get; set; }
}
string
is a reference type, a class. You can only use Nullable<T>
or the T?
C# syntactic sugar with non-nullable value types such as int
and Guid
.
In particular, as string
is a reference type, an expression of type string
can already be null:
string lookMaNoText = null;
System.String
(with capital S) is already nullable, you do not need to declare it as such.
(string? myStr)
is wrong.
Please note that in upcoming version of C# which is 8, the answers are not true.
All the reference types are non-nullable by default
and you can actually do the following:
public string? MyNullableString;
this.MyNullableString = null; //Valid
However,
public string MyNonNullableString;
this.MyNonNullableString = null; //Not Valid and you'll receive compiler warning.
The important thing here is to show the intent of your code. If the "intent" is that the reference type can be null, then mark it so otherwise assigning null value to non-nullable would result in compiler warning.
More info
For a very specific reason Type Nullable<int>
put your cursor on Nullable and hit F12 - The Metadata provides the reason (Note the struct constraint):
public struct Nullable<T> where T : struct
{
...
}
http://msdn.microsoft.com/en-us/library/d5x73970.aspx
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