5

This is just a feasibility question. I know that if I say

   int myInt = "5"; 

I get a compile time error. What I want to do is create compile time errors or warnings on objects. So let's say I have a custom object with a few properties. One of the properties cannot be null otherwise the solution will not compile:

   public static class NoNullObjects
   {
       //NotNullable
       public static NotNullObject {get; set;}
   }

MyClass.cs:

   Line#55   NoNullObjects.NotNullObject = null;

When I build I want to see:

   Error: NotNullObject cannot be set to null. MyClass.cs Line 55.

Is there a way to do this?

Nate Noonen
  • 1,371
  • 9
  • 19
  • See [http://stackoverflow.com/questions/718630/not-nullable-types](http://stackoverflow.com/questions/718630/not-nullable-types) – 3Dave Mar 04 '10 at 19:37
  • This does not solve the OP's question. As the OP requests non nullable reference types. – AxelEckenberger Mar 04 '10 at 19:48

2 Answers2

4

No, not with just C#. Microsoft's Code Contracts work may give you what you want: http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx.

Frank Schwieterman
  • 24,142
  • 15
  • 92
  • 130
  • 1
    I'll just have to wait for .NET 4 then :) Why is what I want to do always in the next iteration? – Nate Noonen Mar 04 '10 at 19:46
  • Nate: You can always download the VS2010 beta which has .NET 4.0. – Fredrik Ullner Mar 04 '10 at 20:04
  • 2
    I used to be big into design by contract, now I'm big into unit testing. From my experience, unit testing is enormously more effective then using asserts / code contracts. I recommend getting into unit testing rather then waiting for code contracts. – Frank Schwieterman Mar 04 '10 at 20:25
0

Here is a question that covers the same topic. The accepted answer suggests that you use code contracts.

Community
  • 1
  • 1
AxelEckenberger
  • 16,628
  • 3
  • 48
  • 70