You should be getting a compiler error telling you that your method doesn't return a value for all possible code paths. Therefore if your if
statement is true then it returns a value but if it is false then it doesn't so you need to return something back.
public Bitmap cropAtRect(Bitmap b, Rectangle r)
{
if (r.Width > 0 && r.Height > 0)
{
Bitmap nb = new Bitmap(r.Width, r.Height);
using (Graphics g = Graphics.FromImage(nb))
{
g.DrawImage(b, -r.X, -r.Y);
};
return nb;
};
return b; //Return original bitmap
}
But now you've introduced a potential problem to callers. Bitmap
needs to be cleaned up. In the if
case you're creating a new bitmap that needs to be cleaned up independent of the original bitmap (hence 2 cleanups). But if the condition is false then you return the original and therefore the original bitmap needs to stay around until you're done with it. Perhaps an example may help.
Bitmap target = null;
using (var source = GetSomeBitmap())
{
target = cropAtRect(source, someRect);
};
//Do something with target...
target.Dispose();
The above code works if the if
statement is true but will fail if it is false. Therefore you need to ensure your documentation clarifies that the original bitmap remain valid until the returned bitmap is no longer needed or you need to create a copy of the bitmap even in the false
condition.