Calling a specific constructor in C # with zero

I have a class with several constructors, and I want to name the "main" one from the other, but using null.

Using only this(null)leads to a compile-time error, so I pass null to the type of another constructor. Compiles fine.

MyClass
{
  public MyClass(SomeType t)
  { }

  public MyClass(IList<FooType> l)
    : this((SomeType)null)
  { }
}

It feels, let's just say icky. Is it good, ordinary, or crazy and shows a flaw in the class - that it should have an empty constructor?

For the class, "mostly" is required SomeType, but there are rare cases when everything is in order so that it does not exist. I want rare times to stick out and be obvious that something is “not typical” with the code.

+3
3

, null . A null , , null .

, , , (no-arg), . , .

+9

. , , .

, , , null, , :

MyClass {

  private MyClass() {
  }

  public MyClass(SomeType t) {
  }

  public MyClass(IList<FooType> l) : this() {
  }

}

( , ) , , :

MyClass {

  public MyClass(SomeType t) {
  }

  public static MyClass CreateEmptyInstance() {
    return new MyClass((SomeType)null);
  }

}
+7

In my honest opinion, this seems like a logical flaw that will lead you to trouble somewhere in the future. It just seems that at some point a piece of code will be written that will perform some verification and break this constructor, and you will spend a lot of time debugging. I need to understand more what exactly you are trying to do and why.

0
source

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


All Articles