I am looking for a way to determine the number of struct objects that are created in my program. It is for educational purposes.
I found this answer on SO, which works for classes: https://stackoverflow.com/a/12276687/363224. So I tried to do something similar with a struct
, but as expected it doesn't work like that.
public struct Car
{
public string brand;
public static int ObjectsConstructed { get; private set; }
public Car(string brand)
{
this.brand = brand;
ObjectsConstructed++;
}
}
...
Car car1 = new Car("VW");
Car car2 = car1; // How can we increment the ObjectsConstructed?
List<Car> carList = new List<Car>();
carList.Add(car1); // How can we increment the ObjectsConstructed?
The Car(string)
constructor is not called, because the copy of the struct object is called some kind of memcpy and doesn't go through the constructor. A struct also doesn't allow explicit parameterless constructors.
How does one make sort of a copy constructor that can be handled? Or is there another way to get this information out of the runtime via reflection?
EDIT
I wrote a test that shows what I mean:
// This test passes, firstCar and sameCar are not the same.
[TestMethod]
public void HowManyTimesIsACarCreated()
{
Car firstCar = new Car();
Car sameCar = firstCar;
sameCar.brand = "Opel";
// It seems that you can change sameCar without changing firstCar
Assert.AreNotEqual(firstCar.brand, sameCar.brand);
// This one is tricky, because firstCar and sameCar are passed as parameters, so new objects would again be created as I would see it.
Assert.IsFalse(ReferenceEquals(firstCar, sameCar));
}
firstCar and sameCar do not point to the same object, since I can change the brand if sameCar, but firstCar is still the same.