2

Feel free to edit 'mutate' from the title if it's a poor choice of wording.

My question is, relatively, simple.

Take the following example:

myCollection.OrderBy(o => o);

How do I know whether OrderBy will/will not order myCollection or whether an assignment (following) is necessary:

myCollection = myCollection.OrderBy(o => o);

Is it a case of having to build it and check every time I encounter an extension I'm unfamiliar with?

Please note: I'm not asking whether this will or will not affect myCollection, I already know the answer to that from using it hundreds of times previous, I'm asking how I'd know.

3 Answers3

5

You can't tell from just the signature.

The best you can do is to investigate the actual code, for example by looking at the .NET Reference Source. Another thing you could do is check the return type. If it is the same as the one it's being called on, it probably doesn't change it, it most likely returns a new instance. Is it a void, then it probably does change something inside.

For your specific case for example, OrderBy: no. See here. It 'just' returns a new OrderedEnumerable.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
2

One way is to find out if the method or its class is marked as [Pure]. Pure code does not modify input values.

Steven Liekens
  • 13,266
  • 8
  • 59
  • 85
  • 1
    "This attribute is not enforced by the current analysis tools; you should use this attribute only if you are sure that the methods are pure." – jltrem Aug 27 '14 at 13:04
  • Assuming that the original developer did exactly that, you can trust that the method is pure. Otherwise, it's probably best to file a bug report. – Steven Liekens Aug 27 '14 at 13:08
2

You can check for the Pure attribute in the class decoration as Steven Liekens said. But in its absence, the only way to know for sure is by:

  • Experimenting: for example, get an instance of the class and serialize it. Use the method and then serialize it. Compare the results. May not be accurate every time.

  • Reverse engineering the method: and I hope you have the source code. If you don't, you can use reflection. This will require some judgement if the method is somewhat complex, but this complexity here is subjective.

  • Reading the docs and trusting them - if the doc is present. This is the sensible thing to do with the .NET Framework types, and an exercize of faith otherwise.

Geeky Guy
  • 9,229
  • 4
  • 42
  • 62