Adventures with Visual Studio: Properties Should Not Return Arrays

Early this morning, I installed the latest update of the Roslyn Code Analyzers in Visual Studio 2019 and was immediately welcomed with this warning: Properties should not return arrays.

Something you need to know about me. I have this weird obsession of needing to remove all the “squigglies” that Visual Studio barks about from my code! This usually results in me just suppressing the error or warning, but this warning intrigued me, and I wanted to dig a little deeper.

Searching around the Internet, I came across this article by Eric Lippert called Arrays considered somewhat harmful.

I will share with you the highlights that convinced me to stop having properties return arrays. These highlights are taken straight from Eric Lippert’s article:

You probably should not return an array as the value of a public method or property, particularly when the information content of the array is logically immutable.

Why? Because now the caller can take that array and replace the contents of it with whatever they please. Returning an array means that you have to make a fresh copy of the array every time you return it.

Eric Lippert

Things that are immutable should not change.

An array is a collection of variables. The caller doesn’t want variables, but it’ll take them if that’s the only way to get the values. But in this case, as in most cases, neither the callee nor the caller wants those variables to ever vary. Why on earth is the callee passing back variables then?

Variables vary. Therefore, a fresh, different variable must be passed back every time, so that if it does vary, nothing bad happens to anyone else who has requested the same values.

Eric Lippert

Interesting.

So what should I being doing?

If you are writing such an API, wrap the array in a ReadOnlyCollection and return an IEnumerable or an IList or something, but not an array.

Eric Lippert

I am going to take some more time and noodle on this, I would be interested to hear others thoughts on this, but in the meantime, I no long return arrays, but rather an IEnumerable.

No more “squiggles” … mission accomplished!

Leave a Reply

Your email address will not be published.