0

I have a class with a property: public MyClass myProperty { get; set; }. When a object is created, this property is null.

I wanted it to automatically call a MyClass() and instantiate this property, and compiler throw error for a myObject.myProperty = null;.

Is it possible to do that in C#? Or do I need to encapsulate a verification in the property's getter?

Hikari
  • 3,797
  • 12
  • 47
  • 77
  • 3
    Why don't you just provide it a default value inline or in the constructor? You can't enforce non-nullness -- at most you can do a runtime check. There is a proposal for this for C# 7 but let's hope that won't go through. – Jeroen Vannevel Mar 16 '16 at 17:31
  • You can't get the compiler to do this, because you could do `myObject.myProperty = someMethodDefinedInAnotherAssembly();` which the compiler can't check. Only a runtime check can be done. – Matthew Watson Mar 16 '16 at 17:35
  • How about using a struct if your `MyClass` is a just a value? – libertylocked Mar 16 '16 at 17:49
  • I provide a default object in constructor, but the property can still be set null later. Ok I get that compiler can't check for possible null from other assembly/dll, so sad. – Hikari Mar 17 '16 at 16:00

0 Answers0