1
votes

I'm trying to port someone else's C# code to Xojo. There is the following definition in a class:

static cpCollisionHandler cpCollisionHandlerDefault = new cpCollisionHandler(
         cp.WILDCARD_COLLISION_TYPE, cp.WILDCARD_COLLISION_TYPE,
       DefaultBegin, DefaultPreSolve, DefaultPostSolve, DefaultSeparate, null
    );

I understand that this is static variable that can be returned from the class without instantiating it. I also understand that it is a property called cpCollisionHandlerDefault and that it returns a type of cpCollisionHandler. What I'm not sure about is does this return a new cpCollisionHandler object every time the property is requested from the class or does it return a new object the first time the property is accessed and then the same reference to that cpCollisionHandler for each subsequent request?

4
It will create a new instance of cpCollisionHandle at the startup then you'll get a reference to that instance.The_Black_Smurf

4 Answers

1
votes

You have it all a bit mixed up. This is a static variable cpCollisionHandlerDefault of type cpCollisionHandler which is instantiated by the new... The static instantiation takes place before all other code executes and the variable is available for the whole run of the app.

1
votes

This is a static field, not a property. From the documentation:

A static field identifies exactly one storage location. No matter how many instances of a class are created, there is only ever one copy of a static field.

So it is instantiated only once, and it does not return a new object every time it is accessed.

With C# 6.0, it is possible to return a new object every time you access a static field, with a slight syntax modification using an expression-bodied member:

static cpCollisionHandler cpCollisionHandlerDefault => new cpCollisionHandler(
     cp.WILDCARD_COLLISION_TYPE, cp.WILDCARD_COLLISION_TYPE,
   DefaultBegin, DefaultPreSolve, DefaultPostSolve, DefaultSeparate, null
);
0
votes

does this return a new cpCollisionHandler object every time the property is requested from the class

No, the program instanciates the field once, the first time the class is loaded

does it return a new object the first time the property is accessed and then the same reference to that cpCollisionHandler for each subsequent request?

Yes, it is the same reference for each request

0
votes

This is actually not a property but a field, i.e. a "variable" on class level. Fields do not have getters or setters like properties but behave exactly like local variables, they just have a different scope.

The cpCollisionHandler object is created the first time the class is loaded during runtime and lives until the application terminates or some other value is assigned to the cpCollisionHandlerDefault field.