Why Elevate Nullable Types?

5/26/2004 10:35:31 PM

Why Elevate Nullable Types?

When I first learned about extended support for nullable types into the C# language? I was surprised. Nullable types should be enhanced through adding libraries and using existing C# support for extending the syntax such as overloaded operators. This is how it would be done in C++.

However, the new nullable types syntax points to a weakness in the design of generics.

The constraints mechanism in CLR generics currently disallows C# operators from being lifted from the underlying base type to their nullable versions. So, if n1 and n2 are nullable types of type V and v1 and v2 are variables of the underlying value types V, the n1 (+) n2 and n1 (+) v2 will not be available even if v1 (+) v2 are. Also, to handle nullable booleans requires C# language support, because the generics mechanism doesn't allow operator true and false to be overloaded.

So, Nullable fails to deliver all the features that existed in currently available nullable types like System.Data.SqlInt32 and SqlBoolean.

Without the extended syntax supports, users of Nullable types would always have to check for a null value before extracting its value. That extra check is always the same code and always has to be done. It results in harder to read code and opportunities for errors to be introduced. There's strong temptation to omit a check.

Instead of forcing the user to write result= a.HasValue && b.HasValue ? a.Value+b.Value : null, the C# designers apparently saw an optimization here. That's probably why nullable types is receiving elevated support in C#.






Net Undocumented is a blog about the internals of .NET including Xamarin implementations. Other topics include managed and web languages (C#, C++, Javascript), computer science theory, software engineering and software entrepreneurship.

Social Media