What is disposable ref structure in C#?

Overview

In C# 7.2 onward, a struct can be declared with the ref keyword. This allows the instances of ref structs to be allocated on the stack and restricts them from moving onto the managed heap. However, this also enforces some limitations over the ref structs, notably that the ref structs cannot implement any interface.

In C# 8.0, a special exception to the above limitation was made for the IDisposable interface.

The IDisposable interface

Classes or structs that implement the IDisposable interface are able to release their unmanaged resources. The logic for releasing the unmanaged resources is written in the void Dispose() function. This function is called by the garbage collector on the object that it’s freeing resources from. If the IDisposable interface is not implemented, only the managed resources will be freed by the garbage collector.

Note: The Dispose function can also be called explicitly inside the program when an object is no longer needed.

Improvement in C# 8.0

If a ref struct or a readonly ref struct implement a void Dispose() method with an access modifier like public or protected, this would be equivalent to implementing the IDisposable interface. This means that the garbage collector would call the Dispose function when freeing resources of the said instance.

Therefore, this feature allows the ref struct and readonly ref struct to be disposed of without specifying that they are implementing the IDisposable interface.

Example

ref struct Temp {
public int[] arr;
public void Dispose() {
arr = null;
}
}

In the above example, the Temp struct has a void Dispose() method that has the public access modifier. Therefore, the IDisposable interface is implemented. The Dispose method will be called when the scope of an instance of Temp concludes.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved