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

Will a String Get-only Lambda property always return a new object, or is it cached?

I have a class I called FileFilter. It is a pretty basic class, whose goal is to facilitate creation of the file filters for file browsing dialogs.


Class FileFilter{

Public Name { get; }
Public Extension { get; }
Public FileFilter => String.Format(“{0}{1}|{1}”, Name, Extension);

}

I don’t anticipate having to access the ‘FileFilter’ property a lot (only when using the dialogs), but figured I could use the object to store the strings for other functions, such as DirectoryInfoGetFiles() could accept the file extension.

So I’ve created a small static class with the various objects, such as ‘TextFile *.txt’

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

My question here is theoretically speaking, is it more efficient to generate the string for FileFilter during object construction, or to use that lambda expression?

If using the lambda expression several times in a row, are new instances created, or is it cached?

I think it would create a new string on first use, store it and reuse it during runtime since it’s always generating the same string, but don’t actually know. OTOH, it’s technically a function, that runs every time, so it could be creating a new string object every time.

I read about string interning, so I’m curious how that plays into this.

>Solution :

First, => in this case is not a lambda, it’s syntax sugar for a read-only property. It’s equivilent to

public string FileFilter
{
    get
    {
        return String.Format("{0}{1}|{1}", Name, Extension);
    }
}

If using the lambda expression several times in a row, are new instances created, or is it cached?

The getter in a property is evaluated each time it is read. This means if you call FileFilter multiple times, String.Format will run multiple times. The two values you use in String.Format, Name and Extension, can only be set by the constructor. This means that once the constructor has finished, FileFilter will return different string objects, but each object will have the same value, no mater how many times you read the property.

You could calculate and cache this value in the constructor after you set Name and Extension, or you can let this trivial amount of code stay as is. That’s up to you.

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