Why do I get Error "The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'"?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using Universe;
namespace Universe
{
public class clsdictionary
{
private string? m_Word = "";
private string? m_Meaning = "";
string? Word {
get { return m_Word; }
set { m_Word = value; }
}
string? Meaning {
get { return m_Meaning; }
set { m_Meaning = value; }
}
}
}
String
is already nullable.
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.
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
Nullable<Nullable<int>>
is disallowed even though Nullable<int>
is a struct.
Success story sharing