Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the lifetime of a property with only a getter

Lets assume I instantiated MyClass. Does my Foo property have a reference at this point or is it null? Also what happens after I call UseFoo() and exit the scope? Did I dispose Foo or just foo?

public class MyClass
{
    private readonly string param;
    private IDisposable Foo => new Foo(param);

    public MyClass(string param)
    {
        this.param = param;
    }

    public void UseFoo()
    {
        using var foo = Foo;
        // use foo
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Q: Does my Foo property have a reference at this point or is it null?
A: No, because the property does not have a backing field, aka state.

Instead, every time you read the value of Foo, you will construct a new instance of the Foo type and return that.

As @juharr so nicely put it in their comment, it is a property but behaves like a method.

Q: Also what happens after I call UseFoo() and exit the scope? Did I dispose Foo or just foo?
A: You disposed the single object that you got from reading the Foo property and stored in the foo local variable.

Since the Foo property does not actually have state, you only disposed the object that was constructed for you when you read the Foo property.

The next time you read the Foo property you will get a new instance.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading