0
    public interface IOperationResult
    {
        bool IsSuccessful { get; set; }
        public string Message { get; set; }
    }

    public interface ICreateCommandOperationResult<T?> : IOperationResult
    {
        public T? InsertedId { get; set; }
    }

When I insert a record in database, I want to return inserted record's Id. But sometimes there are exceptions that in this case I need to send null in InsertedId.

How can I do it?

1
  • 1
    Make your ICreateCommandOperationResult generic on T (i.e., ICreateCommandOperationResult<T>), constrain T to a struct and then use T? as the type of InsertedId Commented Mar 28, 2020 at 21:24

1 Answer 1

1

You can apply the where T: struct generic constraint (or class if you are using C# 8 and need a nullable reference types) and replace T? with just T in ICreateCommandOperationResult interface.

public interface ICreateCommandOperationResult<T> : IOperationResult
    where T : struct //where T : class
{
    public T? InsertedId { get; set; }
}

The example of implementation

public class Test : ICreateCommandOperationResult<int>
{
    public bool IsSuccessful { get; set; }
    public string Message { get; set; }
    public int? InsertedId { get; set; }
}
Sign up to request clarification or add additional context in comments.

3 Comments

The compiler was happy about struct but not about class
@Enigmativity yes, I've pointed it in aswer, that it's valid in C#8 in case of using nullable reference types
@PavelAnikhouski - Yes, Pavel, my comment was directed at Hamid. He may not have understood that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.