The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Email Subscription

    Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 716 other subscribers

.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:

Anyway, back to the error message above.

Lots of people are confused by it, just see a few questions on StackOverflow:

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

 

Discover more from The Wiert Corner - irregular stream of stuff

Subscribe now to keep reading and get access to the full archive.

Continue reading