Force element initialization in C # constructor

Is there a way to raise an error if each constructor does not initialize this member? Maybe something with const?

I want this because I have a bunch of code where I get errors as a result of incorrect calculation of element values. What I really would like to do is get rid of all the mess and follow the compiler’s example when it is executed again (write code that uses the final result, fix errors due to the use of non-existent code, fix errors, etc.). The only step this does not work on is the member variables, because I am not forced to initialize them in the constructors, for example, for local variables.

+3
source share
5 answers

Unfortunately, C # does not offer such built-in predicates. The best you can do is write a method that checks the object in question, either for invalidity or for some predetermined flag value and should be disciplined about calling it at the end of each constructor and / or at the top of each method that refers to the object.

+3
source

It is supported. For example:

  class Test {
    int notAssigned;
    void method() {
      // Use it, but don't initialize it
      int ix = notAssigned;
    }
  }

It produces:

warning CS0649: The 'ConsoleApplication1.Test.notAssigned' field is never assigned and will always have a default value of 0

To turn it into an error, use the tab "Project + Properties", "Assembly", "Process warnings as errors."

+1
source

, , , , . , , , .

public class Foo
{
   private int val1;
   private List<int> list;

   public Foo()
   {
      //could also be a private constructor if that appropriate
      //all default initialization
      val1 = 1;
      list = new List<int>();
   }

   public Foo(int nonDefaultValue1) : this()
   {
      //set inputted value
      val1 = nonDefaultValue1;
      //no need to initialize list, done by default constructor
   }
}
+1
+1

. Visual Studio Shift + F12 ( ). , .

0

Source: https://habr.com/ru/post/1703059/


All Articles