I have an object that is generated in one class
public class CreatingClass { public T CreateObject<T>(Dictionary<string, object> parameters) where T : IMyInterface, new() { .... } public void DestroyObject(IMyInterface objectToDestroy) { .... } }
I call this function from a client class, then at times need to nullify it through my application by the creating class.
Can I do something like the following
public class ClientClass { MyObject obj; CreatingClass creatingClass = new CreatingClass(); private void AFunctionToCreateMyClass() { obj = creatingClass.CreateObject<MyClass>(parameters); } private void AFunctionToDeleteMyObject() { CreatingClass.DestroyObject(obj); Assert.IsNull(obj);//Doesn't fail } }
I had tried objectToDestroy = null, but didn’t think it would work (and it didn’t)
Note that you can’t actually destroy an object; you are subject to the rules of garbage collection. At a push, you could check for
IDisposableand call Dispose(),You can use the
refsamples provided, but I’m not sure there is much point; it is simpler just to clear the field with ‘obj = null;’.The
refusage could get confusing, since that works on the variable – i.e. if you do:then
objwill still be the original value. Unless you have a good reason, I don’t recommend therefapproach.