Fluentassertions: Conversion operators

Created on 30 Apr 2017  路  3Comments  路  Source: fluentassertions/fluentassertions

From the C# Language Specification 搂10.10.3

The signature of a conversion operator consists of the source type and the target type. (Note that this is the only form of member for which the return type participates in the signature.) The implicit or explicit classification of a conversion operator is not part of the operator's signature. Thus, a class or struct cannot declare both an implicit and an explicit conversion operator with the same source and target types.

Because the return type is part of the signature HaveMethod cannot always be used to check for the presence of user conversions.

Example:

public static explicit operator int(MyStruct value)
public static explicit operator string(MyStruct value)

Using typeof(MyStruct).Should().HaveMethod("op_Explicit", new Type[] { typeof(MyStruct) }) fails as it matches multiple methods in MyStruct, namely both.

My local workaround is terribly ugly:

typeof(MyStruct).GetMethods().Should().Contain(m =>
                   m.ReturnType == typeof(int)
                && m.Name == "op_Explicit"
                && m.GetParameters().Length == 1
                && m.GetParameters().Any(p => p.ParameterType == typeof(MyStruct))

It would be much nicer with dedicated functions for implicit and explicit conversion, where one specified the source and target type.
Something like

  • HaveImplicitConversion<TSource, TTarget>(string because = "", params object[] becauseArgs)
  • HaveExplicitConversion<TSource, TTarget>(string because = "", params object[] becauseArgs)
enhancement help wanted

All 3 comments

Say no more - I'll try to implement them.
Stay tuned.

It should be finished now, with only changes to documentation.md missing.
https://github.com/jnyrup/fluentassertions/tree/user-defined-conversions
Would you prefer that I make a PR now or wait until 5.0.0 is finished?

I though had quite some problems running the tests.
I assuming running build.ps1 from PowerShell should do it?
It always failed in unrelated tests to my changes and it varied which other tests failed.
E.g. with "collection was modified" exceptions.
Any pointers?

I think it is best to wait for 5.0. I'm almost ready with PR #558 which involves merging a lot of projects into one. After this is merged, I will accept changes again.

Was this page helpful?
0 / 5 - 0 ratings