.NET/C#: you cannot do string? because Nullable is for value type, and string is a reference type
Posted by jpluimers on 2014/01/15
At clients, I see quite a few people being confused by this compiler error message:
Error 1 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'
One of the reasons about the confusion is that a string variable behaves like a value type, but in fact is a reference type because their values can consume a huge amount of memory (thanks User codekaizen).
A few interesting questions on that on StackOverflow:
- c# – Why strings behave like ValueType – Stack Overflow.
- c# – Why String behaves like value type while using == – Stack Overflow.
- In C#, why is String a reference type that behaves like a value type? – Stack Overflow.
- why string behaves as value type even though it is a reference type in c# – Stack Overflow.
- c# – Why .NET String is immutable? – Stack Overflow.
- .net – Is string a value type or a reference type? – Stack Overflow.
Anyway, back to the error message above.
Lots of people are confused by it, just see a few questions on StackOverflow:
- C# nullable string error – Stack Overflow.
- c# – The type ‘string’ must be a non-nullable type in order to use it as parameter T in the generic type or method ‘System.Nullable’ – Stack Overflow.
- c# – Returning nullable string types – Stack Overflow.
- c# – Why is string nullable? – Stack Overflow.
- .net – Why does trying to use string? (Nullable string) in C# produce a syntax error? – Stack Overflow.
So lets look closely at the error again:
Error 1 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'
It implies that string is either:
- not a value type
- nullable
Jon Skeet has a very nice article C# in Depth: Strings in C# and .NET which, after the basics that string is reference type that is immutable, can contain nulls and overloads the == operator reveals much more insight.
This short list of basic string features is already enough to explain the error message.
Strings fails not one, but both of the features indicated by the error message:
- Stings are not value types
- Strings can be null
--jeroen






Leave a comment