it depends on the use case. as the object is not defined, we do not know the side effects of reading and writing a property.
in your sample, you a setting a value type, which requires no allocation other than the object (unless there are side effects). so pre-allocating the object requires only one memory allocation, vs one per loop. in the sample code the object is only used in the loop and is not used outside, so its all local.
a localized version one might be:
// local scope dateObject, so it unavailable outside the loop
{
DateObject dateObject = new DateObject();
for (int i = 1; i < lines.Length; i++)
{
dateObject.DateOnly = <some value>
}
}
this limits the dateObject property changes to the loop. but if the loop is only accessing a couple properties of an object, maybe it should access a copy of the properties, or not use the object at all.
DateObject dateObject = new DateObject();
...
// local scope with guard
if (dateObject != null)
{
// anonymous object with copy of property values
var temp = new { DateOnly, OtherProp};
for (int i = 1; i < lines.Length; i++)
{
temp.DateOnly = <some value>;
}
}
again a DateTime is a value type the follow works with no allocations:
DateObject dateObject = new DateObject();
...
for (int i = 1; i < lines.Length; i++)
{
var temp = dateObject.DateOnly;
temp = <some value>;
}