Home > Mobile >  Delegate parameter in interface method
Delegate parameter in interface method

Time:01-03

I apologise in advance as I feel like I'm going to explain what I want to do really badly.

I have a number of models in my application, each of them implements an interface named "IDatabaseItem", I want each "IDatabaseItem" to have a Delete method which returns true or false, but I also want the method to take in a delegate(string) so when the delete method is performed, I can return a string result too as to whether the operation was successful or not. This will also allow the caller to deal with the result however they so choose. In my application this could be something like a pop-up in the UI.

Here's kind of how I thought I'd implement such a thing.

    public interface IDatabaseItem
{
    int Id { get; }
    DateTime Date { get; }

    delegate void DBOperationResult(string result);

    bool Delete(DBOperationResult foo);
}

I get a compiler result when attempting the above: Error CS8370 Feature 'default interface implementation' is not available in C# 7.3. Please use language version 8.0 or greater.

From reading other posts, I think I might be barking up the tree and that Delegates and Interfaces do not mix. But any help would be appreciated.

CodePudding user response:

The declaration of a delegate is a type itself, like declaring an interface or a class. Interfaces do not support nesting types in C# 7.3 and prior. To get your code working, you have to move the delegate declaration to the outer scope.

public delegate void DBOperationResult(string result); // a type itself

public interface IDatabaseItem
{
    int Id { get; }
    DateTime Date { get; }

    bool Delete(DBOperationResult foo);
}

With the introduction of 'default interface implementations' in C# 8.0 interfaces have been extended to permit the declaration of nested types (like your delegate).

See https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods for more details.

  • Related