-2

I am using a library which measure metrics for running code. The usage of the library is something like this.

_Library.Wrap("AnyStringForMetrics", Func<T>);

So whatever I pass into the Func as a lambda will be measured and result of it will be returned.

At the moment, I have method where I want to measure this line where it tries to create or get a user with that id. (newlyCreated will be true if the user was created)

public User GetOrCreate(long id, out bool newlyCreated) {
    // some random checks
    return UserDatabase.GetOrCreate(id, out newlyCreated);
}

But now, if I try to wrap my code around

public User GetOrCreate(long id, out bool newlyCreated) {
    // some random checks
    return _Library.Wrap(
        "UserGetOrCreate", () => UserDatabase.GetOrCreate(id, out newlyCreated));
}

I will get an exception for using "out" inside lambda expression. How should I resolve this?

If possible please write out a concrete code example... Thanks.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
Zhen Liu
  • 7,550
  • 14
  • 53
  • 96
  • 1
    Use a [ValueTuple](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples) as return type instead. `public (User user, bool newlyCreated) GetOrCreate(long id) { var user = ....; bool created = ....; return (user, created); }` and map it to `Func<(User, bool)>`. – Olivier Jacot-Descombes Jun 02 '21 at 19:48
  • @OlivierJacot-Descombes could you put in an answer? I think this might work. I can accept. – Zhen Liu Jun 02 '21 at 20:00
  • nvm looks like they decided this question is duplicate so cannot answer. I tried your method it works. – Zhen Liu Jun 02 '21 at 20:11

1 Answers1

1

Use a ValueTuple as return type instead and thus avoid using an out parameter.

public (User user, bool newlyCreated) GetOrCreate(long id) {
    var user = ....;
    bool created = ....;
    return (user, created);
}

and map it to Func<(User, bool)>.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188