The Substring
method of C#'s string
class (which is also available in every other .Net language) does not seem to alter state and will always return the same value, given the same arguments.
So is it a "pure
" method?
I'm asking, because in Microsoft's reference source code of the System.String
class, many other public methods are annotated as [Pure]
(like Trim
, Compare
, IndexOf
, Equals
), but the Substring
method is not.
1 Answer 1
Note that Microsoft uses [Pure]
exclusively in the context of Code Contracts (as opposed to, say, optimizing code during compilation or runtime). In this context, if the method doesn't make visible state changes, the method is pure. As simple as that.
When Code Contracts were introduced, the [Pure]
attribute was added sporadically and sometimes inconsistently, and a series of methods which are pure didn't have this attribute. Back then I was working on several critical projects which required us to use Code Contracts, and I had to do a lot of wrappers around .NET Framework's assemblies just to add proper contracts, for instance saying that Random.NextDouble
will always return a value which is greater than or equal to 0.0 and less than 1.0. The same goes for [Pure]
.
Chances are, some developers at Microsoft needed to work with string.Trim
within the code covered by Code Contracts, and so it got its attribute, but nobody used string.Substring
. Or there may be other considerations why the later didn't receive its well deserved attribute.
Anyway, if you rely on Code Contracts, create a wrapper and add the missing attribute.
If you don't rely on Code Contracts, ignore those attributes.
-
1
[Pure]
has some other minor advantages outside Code Contracts - for example, some linters will pick up if the return value of a pure function isn't used.Philip Kendall– Philip Kendall2020年07月27日 09:13:48 +00:00Commented Jul 27, 2020 at 9:13
Substring
callingInternalSubString
, the latter of which markedunsafe
due to pinning, would have explained why it cannot be marked asPure
despite meeting its practical requirements from a human understanding perspective.Substring
method is quite common, but I think it's OK.string
on which the method is called) should not be changed, themselves?