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")
}
DateTime
and TimeSpan
are not-nullable since they are struct
s rather than class
es.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With