---
source: boltffi_bindgen/src/render/csharp/templates.rs
expression: template.render().unwrap()
---
// <auto-generated>
// This file was generated by BoltFFI. Do not edit.
// </auto-generated>
#nullable enable

using System;
using System.Threading;

namespace Demo
{
    /// <summary>
    /// Mutable counter held over FFI.
    /// </summary>
    public sealed class Counter : IDisposable
    {
        private IntPtr _handle;

        // Private handle-adopting ctor; used only by chained `: this(...)` and the static factories below.
        private Counter(IntPtr handle)
        {
            _handle = handle;
        }

        /// <summary>
        /// Creates a counter starting at zero.
        /// </summary>
        public Counter()
            : this(CounterNewHandle()) { }

        private static IntPtr CounterNewHandle()
        {
            return NativeMethods.CounterNew();
        }

        /// <summary>
        /// Returns the current value.
        /// </summary>
        public int Get()
        {
            ThrowIfDisposed();
            return NativeMethods.CounterGet(_handle);
        }

        /// <summary>
        /// Adds one to the current value.
        /// </summary>
        public void Increment()
        {
            ThrowIfDisposed();
            NativeMethods.CounterIncrement(_handle);
        }

        /// <summary>
        /// Static factory returning zero.
        /// </summary>
        public static int Zero()
        {
            return NativeMethods.CounterZero();
        }

        internal IntPtr RawHandle => _handle;

        private void ThrowIfDisposed()
        {
            if (_handle == IntPtr.Zero) throw new ObjectDisposedException(nameof(Counter));
        }

        public void Dispose()
        {
            IntPtr handle = Interlocked.Exchange(ref _handle, IntPtr.Zero);
            if (handle == IntPtr.Zero) return;
            NativeMethods.CounterFree(handle);
            GC.SuppressFinalize(this);
        }

        ~Counter()
        {
            Dispose();
        }
    }
}
