Search code examples
c#constructorout

Constructor with output-parameter


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.


Solution

  • Well, the design of that class is broken anyway, so let's break it a bit more (NOTE! I do not recommend this approach!):

    void Main()
    {
    
    }
    
    public class ClassA
    {
        public ClassA(out bool success)
        {
            success = true;
        }
    }
    
    public class B: ClassA
    {
        private static bool success;
    
        // call the constructor from ClassA but without the out-param
        public B()
            : base(out success)
        {
        }
    }
    

    Other than that, the closest you can get is making a factory method:

    public class B : ClassA
    {
        public static B Create()
        {
            bool success;
            var result = new B(out success);
            if (success)
                return result;
            // TODO: Dispose result?
            throw new StupidProgrammerException();
        }
    }