6

Possible Duplicate:
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<T>’

As the title says, why are strings nullable by default in C#, but if I want, say, ints or doubles to be null, I have to explicitly say so?

Community
  • 1
  • 1
Paul McLean
  • 3,450
  • 6
  • 26
  • 36

1 Answers1

12

Because string is a reference type, deriving from object and [most] other default types are value types, deriving implicitly from System.ValueType;

RJ Lohan
  • 6,497
  • 3
  • 34
  • 54
  • 4
    +1. "deriving from `struct`" is not exactly true - http://msdn.microsoft.com/en-us/library/s1ax56ch(v=vs.100).aspx : "All value types are derived implicitly from the System.ValueType." – Alexei Levenkov Jan 17 '13 at 01:29
  • 1
    And [ValueType](http://msdn.microsoft.com/en-us/library/system.valuetype.aspx) also derives from object, but that doesn't mean it is a reference type. Your statement is mostly accurate but I'd consider rewording a little – psubsee2003 Jan 17 '13 at 01:40
  • Good points, the provided link is certainly more complete than my one-liner. – RJ Lohan Jan 17 '13 at 02:18
  • 5
    This isn't a good answer. It is merely stating the obvous. WE KNOW IT'S A REFERENCE TYPE, WE WANT TO KNOW WHY! I get that in C++ string is a class and not a primitive but C# is NOT C++ and has many differences (including how it handles 'primitives'). So why not handle string as a Value Type and not a Reference Type? – Sellorio Aug 14 '13 at 23:35
  • @psubsee2003 The class `System.ValueType` itself is a reference type. For example you can say `ValueType vt1 = null;` or `ValueType vt2 = DateTime.Now; /* boxing */`. But `DateTime` is an example of a value type. – Jeppe Stig Nielsen Jan 19 '15 at 14:08