C# Object-Oriented – Create New Object or Reset Properties

cconstructionobject-oriented

 public class MyClass
    {
        public object Prop1 { get; set; }

        public object Prop2 { get; set; }

        public object Prop3 { get; set; }
    }

Suppose I have an object myObject of MyClass and I need to reset its properties, is it better to create a new object or reassign each property? Assume I don't have any additional use with the old instance.

myObject = new MyClass();

or

myObject.Prop1 = null;
myObject.Prop2 = null;
myObject.Prop3 = null;

Best Answer

Instantiating a new object is always better, then you have 1 place to initialise the properties (the constructor) and can easily update it.

Imagine you add a new property to the class, you would rather update the constructor than add a new method that also re-initialises all properties.

Now, there are cases where you might want to re-use an object, one where a property is very expensive to re-initialise and you'd want to keep it. This would be more specialist however, and you'd have special methods to reinitialise all other properties. You'd still want to create a new object sometimes even for this situation.

Related Topic