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

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

    Join 1,512 other followers

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: