everything. I have never worked with destructors or disposed of, so this is new to me. I have the task of making a class that has destructor and deletion methods, and has an UInt64Id property that is automatically incremental, and a static property Dictionary<UInt64,MyClass>that should reference Id all live instances MyClass.
After searching how to use them correctly, this is what I ended up with:
public class MyClass : IDisposable
{
private static Object Lock = new Object();
private static Dictionary<UInt64, MyClass> LiveInstances = new Dictionary<UInt64, MyClass>();
public UInt64 Id { get; private set; }
public MyClass()
{
lock (Lock)
{
var newId = IncrementalId();
if (newId == 0)
{
throw new ArgumentException("Reached MAX VAL");
}
Id = newId;
LiveInstances.Add(Id, this);
}
}
~MyClass()
{
CleanUpNativeResources();
}
public void Dispose()
{
lock (Lock)
{
CleanUpManagedResources();
CleanUpNativeResources();
GC.SuppressFinalize(this);
}
}
protected virtual void CleanUpManagedResources()
{
LiveInstances.Remove(Id);
}
protected virtual void CleanUpNativeResources()
{
}
private static UInt64 IncrementalId()
{
for (ulong i = 0; i <= Convert.ToUInt64(LiveInstances.Count) ; i++)
{
if (i != UInt64.MaxValue && !LiveInstances.ContainsKey(i + 1))
{
return i+1;
}
}
return 0;
}
}
Now, my question is: How do I place objects? I try to find examples of deleting objects, I find something like this:
// Code to dispose the managed resources of the class
Console.WriteLine("Object disposed");
Thanks in advance.
source
share