how to return null from a constructor

say, i a m trying to do something like:

class something

something(streamreader){

if (wrong format or end of file)

caller receives null as result

else

build object from what has been read in file

}

i tried 'return null', but it says it can not do that since a constructor is 'void', so i can not place a return sentence. i'm not sure something like this.dispose would retunr a null, since the 'dispose' may be asynchronous (or something)

i have the next alternative

class something blah blah

somehting(string)

(build object from string, check if string==null or wrong format before calling)

static bool checkformat(string)

check to see if string is adecuate to build something object

but if i use this, that would mean that i have to parse the string twice, onece to check format and once to build it, so im not too in favour of it, how do i return null from a cosntructor if params are not adecuate



Answer this question

how to return null from a constructor

  • Hatzi74

    well because exceptions are expensive and because it's the way the design pattern is really. Maybe the same reason for C/C++ (I dont dev in C/C++)

    It's just not recommended and I've not seen any classes that throw an exception via the constructor, except for maybe invalid inputs but even then its recommended to check/validate your inputs before constructing an object - its better design.



  • millie_w

    Note, it is not a bad practiceto throw an exception is a ctor (either in C# or C++).

    It isa bad practice to allow an exception to leave an object in a "half-constructed" state.

    For example (in C++):

    class MyClass
    {
    char* ptr1;
    char* ptr2;

    public:
    MyClass()
    {
    ptr1 = new char[100];
    ptr2 = new char[10000];
    }
    }

    In that example, if the new for ptr2 throw an out of memory exception, the memory of ptr1 would be lost as a memory leak. The ctor should be written as:

    MyClass()
    {
    ptr1 = NULL;
    ptr2 = NULL;

    try {
    ptr1 = new char[100];
    ptr2 = new char[10000];
    }
    catch(...)
    {
    delete[] ptr1;
    delete[] ptr2;
    throw;
    }
    }



  • Scott Allen - OdeToCode.com

    it wouldnt be recommended and its bad practice. you should really validate your inputs/objects before creating the class object

  • ImagineNation

    Ahmedilyas: "it wouldnt be recommended and its bad practice. you should really validate your inputs/objects before creating the class object "

    No mate. Validating a function's (or constructor's) arguments outside the function itself is the bad practice. If the function's interface changes even a tiny bit, you have a lot of search/replacing to do or you'll be throwing exceptions anyways.

    And arguments about exceptions are way more expensive than the exceptions themselves. Since they're only supposed to be used in *exceptional* circumstances, they should never slow anything down in normal use. Especially in a constructor, where there's just been a slow memory allocation.

    Bad practice is obfuscating and duplicating code to avoid throwing exceptions.

  • Derek Ekins

    hmm.. i think i didnt make myself clear.. a constructor, whether is called a constructor or not, is a function, it returns something, actually a pointer to some object of the type of the class it was declared. a variable declared as some kind of object, or whatever inherits form 'object' class, can point to that type of object or have a null value, now, if i call a function and that function returns null for an object, thats a valid value. i am asking how to do that in a constructor. for example, if i was talking about 'plain c', and i made an alloc or malloc or whatever, it may return the pointer to the allocated space or it may return a null if it was not possible to allocate the space. i want to return the object if the object was created succesfully or null if the parameters to create the objet in the cosntructor function, which is an ordinary function in most senses, stated to return an object of some class, are not adecuate
  • aharuray

    It isn't bad practice to throw an exception from a constructor. If the inputs are invalid or the object cannot be constructed then you should throw exceptions as with any other member. You have to write your class with no control over how it will be called (unless it is an internal class) so the only defence you have against invalid inputs is exceptions.



  • Guenter

    What about making your constructor throw an exception when it isn't created properly, and then use try and catch statements in the function that's calling the constructor
  • PavanKR_ind

    Hi,
    you can't return null in the constructor. You can try and change the way you're doing things, e.g: you could have a class that would check these parameters for you and if they were correct then it would create an instance of "something" or you could have a method in "something" called Initialize that would perform these kind of verifications and then you could return null.


  • Ben Santiago

    I don't think the original question has been resolved. The OP is talking about "validating twice." This is exactly why I say not throwing exceptions from a constructor is bad practice.

    As far as I can see, there are only two proper ways to safely handle object initialization:
    • Throw exceptions from the constructor
    • Don't use exceptions, use empty constructors, and have an Init() method with a return value to indicate success or failure
    Throughout the .NET framework, the first choice is prevalent.

  • Logic Rules

    Also note that it is NOT the constructor that is returning the constructed object, but the new operator.

    I'm curious - why is it bad practice to throw an exception in a constructor I know this is frowned upon in C++ - is the same true for C#, and why


  • Johnnie B.

    Another option would be to create the class with a private constructor and include a static factory method to validate the input parameters before calling the constructor to create the return object. If the input fails validation then you could return null or throw an exception. Of course, this is not a useful option if the class in question will be base type for other classes.

    public class Something
    {
    private Something(int someInput)
    {
    //Initialize object
    }

    public static void Create(int someInput)
    {
    if(someInput is not valid)
    {
    return null;

    }

    return Something(someInput);

    }

    }


  • 2V.

    it seems thats what i must do, but as stated above, i was trying to avoid that, since i would have to check for validity twice. im not happy about it tough
  • Curtis the Analyst of Doom

    a constructor doesnt return anything. It's only job in life is to construct the object. That's all. Nothing else.

    you can only return a value if the method has a return type (non void). also you can return null from string return types or other objects, except for say, integer values



  • spshah

    ah well we have our own views but I still wouldnt recommend it. Always been told throwing an exception in a Constructor is not the way to go about doing things and should be validated before hand before constructing an object.

    as long as the original question is resolved...



  • how to return null from a constructor