locked
what does the '~' character do in this code sample RRS feed

  • Question

  • I've been reading an article(which I should do more often) and found the tilda character '~' confusing...

    public class Render2JPG : FrameRenderer
    {
       public Render2JPG(string img1, string img2)
        {
            g = null;
            g2 = null;
            bmp = null;
            bmp2 = null;
            jpg1 = new Bitmap(img1, true);
            jpg2 = new Bitmap(img2, true);
        }
        ~Render2JPG() // <-------- what does the '~' do?
        {
            jpg1.Dispose();
            jpg2.Dispose();
            bmp.Dispose();
            bmp2.Dispose();
            g.Dispose();
            g2.Dispose();
        }
    

    what does the '~' do.  By the content of the code block that follows that line I'm assuming this is executed when the object is disposed?


    my code is perfect until i don't find a bug

    Saturday, November 28, 2020 11:03 AM

Answers

    • Marked as answer by Christ Kennedy Saturday, November 28, 2020 2:17 PM
    Saturday, November 28, 2020 11:13 AM
  • Hi,

    in C# objects can have Constructors and Destructors :

    public class Poco {
       // constructor called to initialize the object
       Public Poco() {
       }
    
       // destructor called when finalizing the object
       ~Poco() {
       }
    }

    Best Regards.

    • Marked as answer by Christ Kennedy Saturday, November 28, 2020 2:16 PM
    Saturday, November 28, 2020 11:19 AM

All replies

    • Marked as answer by Christ Kennedy Saturday, November 28, 2020 2:17 PM
    Saturday, November 28, 2020 11:13 AM
  • Hi,

    in C# objects can have Constructors and Destructors :

    public class Poco {
       // constructor called to initialize the object
       Public Poco() {
       }
    
       // destructor called when finalizing the object
       ~Poco() {
       }
    }

    Best Regards.

    • Marked as answer by Christ Kennedy Saturday, November 28, 2020 2:16 PM
    Saturday, November 28, 2020 11:19 AM
  • There are two means

    A bitwise operator

    int value = -23;
    var negate = ~value + 1;
    Console.WriteLine(negate);
    or a finalizer as per Microsoft docs,


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    My GitHub code samples
    GitHub page

    Check out:  the new Microsoft Q&A forums


    Saturday, November 28, 2020 11:20 AM
  • thanks for your comment,

    I'm familiar with the bitwise use of '~' but thanks for your reminder.


    my code is perfect until i don't find a bug

    Saturday, November 28, 2020 2:16 PM