How to return a bitmap in a method after wrapping it with IF condition ?

Sharon Lipman 21 Reputation points
2022-10-04T19:43:18.98+00:00
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;  
                }  
            }  
        }  

after adding the line

if (r.Width > 0 && r.Height > 0)  

because i want to make sure it's a rectangle and not just a line now the method is not returning the nb variable.

Developer technologies | Windows Forms
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,326 Reputation points
    2022-10-04T21:33:19.423+00:00

    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.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.