Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not nullable types

Tags:

c#

Is there a way to create a non nullable type in C# (like DateTime or TimeSpan).?

Also is there a way (an attribute maybe) to enforce that not null arguments wouldn't be passed to methods and properties without adding

if(arg1 == null)
{
   throw new ArgumentNullException("this attribute is null")
}
like image 453
Sergej Andrejev Avatar asked Apr 05 '09 09:04

Sergej Andrejev


2 Answers

DateTime and TimeSpan are not-nullable since they are structs rather than classes.

As for your second question, there is no standard way you can do this in C#. You can do this using PostSharp, which is an AOP framework, or with Spec#, which is a whole new language (an extension of C#) which allows for some of desired behavior.

like image 163
Anton Gogolev Avatar answered Sep 28 '22 00:09

Anton Gogolev


The null-checking you refer to will be easier in .NET 4.0 / C# 4.0 via code-contracts, which does pretty much what you want.

Structs are already non-nullable, but don't go creating your own structs like crazy - you rarely need them (classes are far more common). There is no real concept of a "non-nullable class"; people have proposed syntax changes like:

void Foo(string! arg1) {...}

which would have the compiler do the non-null check on arg1 - but in reality, code-contracts does this and more. There are some things you can do in PostSharp, but it probably isn't worth the hastle.

One other thought on a non-nullable class (and one of the reasons they aren't implemented); what would default(T) be for a non-nullable class? ;-p The spec demands that default(T) is well defined...

like image 35
Marc Gravell Avatar answered Sep 28 '22 00:09

Marc Gravell