Search code examples
c#dispose

Generate and Dispose before using?


Today my intstructor, where I'm intern, said I should use

    HImage hi = null;

    HOperatorSet.GenEmptyObject(out hi);
    hi.Dispose();

    hi = f.GrabImageAsync(-1.0);

Instead of

    HImage hi = null;

    hi = f.GrabImageAsync(-1.0);

Prototypes of used functions as follows

    void HOperatorSet.GenEmptyObj(out HObject emptyObject);
    HImage HFramegrabber.GrabImageAsync(double maxDelay);

I respect my instructor ,but I don't see any meaningful explanation at creating and disposing an object before calling hi = f.GrabImageAsync(-1.0); as that functions returns an instance of that object and therefore no need for Generating and Disposing object first, at least in my opinion.

So anyone can clarify if it is really needed or not. Thank you in advance.


Solution

  • I agree with you. Generally there is no use in creating and immediately disposing a variable.

    As far as we can see from the code, HOperatorSet.GenEmptyObject doesn't interact with your f variable, so there would be no meaning in calling that method.

    Also, there is no point in setting HImage hi to null, since that is probably the default already and it is set using the out parameter.

    So my bet would be on:

    HImage hi = f.GrabImageAsync(-1.0);