Reputation: 852
i create this class and it have this constructor :
public class ReturnResult : ImplicitReturnResult
{
public bool Success { get; }
public ResultStatus Status { get; }
public string Message { get; }
public ReturnResult(bool Success, ResultStatus Status, string Message = null)
{
this.Success = Success;
this.Status = Status;
this.Message = Message ?? Status.ToDisplay();
}
}
and in this class i need to use constructor this class :
public class ImplicitReturnResult
{
public static implicit operator ReturnResult(OkResult result)
{
return new ReturnResult(true, ResultStatus.Success);
}
}
i using this code but it show me this error :
Error CS0556 User-defined conversion must convert to or from the enclosing
whats the problem ? how can i solve this problem ????
Upvotes: 1
Views: 1858
Reputation: 239664
In order for the C# compiler to not have to search through all types from all referenced assemblies to find whether any particular user-defined operator exists for a conversion, the rules are that either the input parameter or the return type of any user-defined conversion must match the type in which the operator is defined.
public class ImplicitReturnResult
{
public static implicit operator ReturnResult(OkResult result)
{
return new ReturnResult(true, ResultStatus.Success);
}
}
Neither the return type (ReturnResult
) nor the parameter (OkResult
) to this operator is ImplicitReturnResult
. That's why it's not allowed. You need to move this operator into ReturnResult
itself, not its base class.
It's not enough that one type inherits from the other. It has to be an exact type match.
Upvotes: 3