Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "clear" an object?

Tags:

c#

What's the better way to clear an object:

  1. Write a method inside the class that clears all the members of the class: MyObject.Clear();

  2. Inside my code, in the business logic, null the object: MyObject = null;

like image 686
frenchie Avatar asked Jan 18 '11 20:01

frenchie


People also ask

How do you clear the value of a object?

Use a for..in loop to clear an object and delete all its properties. The loop will iterate over all the enumerable properties in the object. On each iteration, use the delete operator to delete the current property. Copied!

How do I delete a whole object?

The only way to fully remove the properties of an object in JavaScript is by using delete operator. If the property which you're trying to delete doesn't exist, delete won't have any effect and can return true.

How do I remove all objects from a key?

The _. omit function takes your object and an array of keys that you want to remove and returns a new object with all the properties of the original object except those mentioned in the array. This is a neat way of removing keys as using this you get a new object and the original object remains untouched.


1 Answers

They do different things. Setting a variable to null does nothing to the object itself. It may mean that the object is now eligible for garbage collection, but it will make no difference if there are other "live" reference to the same object.

What should you do? Well, it entirely depends on your situation. If you have lots of different places with reference to the same object, and they should all see the "clearance", then modify the object. If you just need one variable to refer to a different object or no object at all, just change the value of the variable.

The important thing is to know the difference between the two - be very aware that the value of a variable is never an object... it's either a reference or a value type value.

like image 181
Jon Skeet Avatar answered Sep 22 '22 17:09

Jon Skeet