Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List<string> assignment and initialization with new List<string> getting error

I’m developing a website with Asp.Net core 3.1 and C# version 8.0. I have a class named "ApiResult"

public class ApiResult
{
    public bool IsSuccess { get; set; }
    public List<string> Message { get; set; } = new List<string>();
    public object Data { get; set; }
}

and I’m going to use it on a controller

public async Task<string> CreateBook(BooksCreateEditViewModel ViewModel)
    {
        if (await _UW.BookRepository.CreateBookAsync(ViewModel))
        {
            return new ApiResult
            {
                IsSuccess = true,
                Message = new List<string> { "Your job has done" } ,
            };
        }
        else
            return "We got an error!!!";
    }

But unfortunately, I got a weird error: "Cannot implicity convert ApiResult to the string"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try changing the return type of your CreateBook method to return Task<ApiResult>. You should then also tweak what you return from your else clause – perhaps set the isSuccess property from your ApiResult model to false. Something along these lines:

public async Task<ApiResult> CreateBook(BooksCreateEditViewModel ViewModel)
    {
        if (await _UW.BookRepository.CreateBookAsync(ViewModel))
        {
            return new ApiResult
            {
                IsSuccess = true,
                Message = new List<string> { "Your job has done" } ,
            };
        }
        else
            return new ApiResult
            {
                IsSuccess = false,
                Message = new List<string> { "We got an error!!!" } ,
            };
    }

You could simplify the if statement so that you don’t create the ApiResult object in two different places, this answer is just given as an example.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading