0

I have two contructors that are conflicting and I don't know how I could handle this situation.

public NotFoundError(string name, object key, int code = 0)
: base($"Entity '{name}' ({key}) was not found.")
{
    Code = code;
}

public NotFoundError(string message, int code = 0)
    : base(message)
{
    Code = code;
}

If I do the following:

throw new NotFoundError(nameof(Customer), request.Id);

It picks the second constructor instead of the first. I know that it happens because it could match with either of them. However, I would like to keep the first constructor because in 99% of the cases, the message will look like that and I don't want to add the message to every exception. For both cases I need the ability to overwrite the error code.

Tom el Safadi
  • 6,164
  • 5
  • 49
  • 102

2 Answers2

4

You could use some factory methods if it's not too cumbersome. Make those ctors private:

public class NotFoundError
{
   // private ctors
   public static NotFoundError ForEntity(string name, object key, int code = 0)
   {
     return new NotFoundError(name, (object)key, code);
   }

   public static NotFoundError WithGenericMessage(string message, int code = 0)
   {
     return new NotFoundError(message, code);
   }
}
CakePlusPlus
  • 943
  • 7
  • 15
2

Use named parameters. The compiler will choose the constructor with the matching names.

throw new NotFoundError(name: nameof(Customer), key: request.Id);

or

throw new NotFoundError(message: "Hello world");
John Wu
  • 50,556
  • 8
  • 44
  • 80
  • Thanks, I already added that solution to the comments of my question. However, new developers could miss this and use the wrong constructor by accident. Still a vaild answer though! – Tom el Safadi Jul 07 '23 at 17:56