Can I declare TCriticalSection object as a public class field?

critical-section, delphi

Solution

The simple answer is yes. A field of a class is a perfectly normal place to hold a `TCriticalSection`.

In order for a critical section to be able to serialize access to a shared resource, all threads must refer to the same instance of the critical section. So, from that fact you conclude that you need to make sure that all threads refer to the same instance of the class. Then when they read the critical section field of that class, all threads are accessing the same instance of the critical section.

It is usually considered to be bad practice to declare public fields. You would normally expose such a thing through either a property, or methods of the class.

Problem

Can I have a `TCriticalSection` object declared as a public field, such as: ``` type TMyObject = class public CS: TCriticalSection; end; ``` I would like to make that field public to allow any thread enter and leave the critical section object, which internally protects integrity of the `TMyObject` instance. So, can I declare `TCriticalSection` object as a public class field ?

Original source