today I saw a snipped that looked really horrible to me, but unfortunetly I cannot simply change it, so I wonder if I can bypass this somehow. I have a class with a constructor that has an output-parameter for success. But that looks really ugly to me. And now when deriving from this class I have to take this param with me- if I want to or not.
class ClassA {
ClassA(out bool success) {...}
}
class B: ClassA {
// call the constructor from ClassA but without the out-param
}
So I´d know if its good practise or if not how I can avoid declaring the out-param from ClassB.
You can do something like this:
It's ugly, but at least you get rid of the out parameter if so you want.
While passing
ref
orout
parameters to a constructor is ugly, there are some types where attempts to create a usable instance will have side-effects, and might fail after some of those side-effects have already occurred. If it is not possible to construct a valid object, the only ways via which the constructor can pass information to the caller are by storing it in athreadstatic
field, encapsulating it within the thrown exception, storing or feeding it to a passed-in object or delegate, or writing it to aref
/out
parameter. Of those, only theref
/out
parameter makes obvious the existence of information with which the client code should be doing something.The existence of
ref
orout
parameters is often an indication that a constructor should beprotected
, and that outside code should go through a factory methods which ensure that if an exception is thrown the passed-out object will get used suitably. For a class to reasonably support inheritance, however, it must offer at least one constructor which is visible outside it. Having that constructor use anout
orref
parameter may be the least evil way for a class to let a caller know what things will need cleaning up if construction fails.Well, the design of that class is broken anyway, so let's break it a bit more (NOTE! I do not recommend this approach!):
Other than that, the closest you can get is making a factory method: