Interface reference counting

Top  Previous  Next

What is translated > Types > Records, Classes, Interfaces > Interfaces > Interface reference counting

In Delphi, interfaces implement automatic reference counting by default. This mechanism manages the lifetime of objects that implement interfaces, using AddRef and Release to track references and destroy the object once the count reaches zero. This is crucial for memory management in Delphi’s interface-based programming model.

 

In contrast, C# uses a garbage collector to manage object lifetime. Reference counting is not built into the language, and interface references do not influence object disposal unless explicitly implemented.

 

Because of this difference, Delphi2C# does not implement real reference counting by default. Instead, it provides placeholder methods to simulate Delphi’s AddRef and Release, primarily for compatibility with existing Delphi idioms.

 

Default Simulation in TInterfacedObject

 

 

public class TInterfacedObject : TObject, IInterface

{

   public uint AddRef() => 1;

   public uint Release() => 1;

}

 

 

- These methods do nothing, but allow the code to compile and behave as expected in typical .NET usage.

- No object destruction is triggered via Release, since .NET relies on garbage collection.

- If you assign and release interface references in translated code, no memory leaks or premature disposals occur, because .NET handles it automatically.

 

 

 

 

 



This page belongs to the Delphi2C# Documentation

Delphi2C# home  Content