Convert string to object based on schema

Viewed 25

I am trying to understand how converting strings to objects works in C#. So I have the following string:

public async Task<String> FunctionReturningReponse() {
     var response = "{'ReponseText': 'Some Text'}";
     return response
}

Now I created a schema as following:

public class TriggerResponse
{
    public string? ReponseText { get; set; } = string.Empty;
}

Can I somehow use this schema to convert my string above to the object of type TriggerReponse so that I can avoid the error in this code:

public class TriggerEmailSendingQueryHandler : IRequestHandler<TriggerEmailSendingQuery, TriggerResponse>
    {
        private readonly IConfiguration configuration;

        public TriggerEmailSendingQueryHandler(IConfiguration configuration)
        {
            this.configuration = configuration;
        }

        public async Task<TriggerResponse> Handle(TriggerEmailSendingQuery request, CancellationToken cancellationToken)
        {
            IConfigurationSection pcConfig = configuration.GetSection(PolicyCenterClient.PC_CONFIG_SECTION);

            var triggerResponse = await FunctionReturningReponse();

            return triggerResponse;
        }
    }

Because when I return triggerResponse which is a string returned from the first function I get this error: Cannot implicitly convert type 'string' to 'Services.Schema.TriggerResponse' [Application]

1 Answers

This is a simple type mismatch - you declare that you are going to return a TriggerResponse in the Handle() task, but attempt to return a string

Why not just update the FunctionReturningReponse() to return the proper type? No casts necessary, as to be honest a cast isn't possible here nor is it desirable

public async Task<TriggerResponse> FunctionReturningReponse() {
    string response = "{'ReponseText': 'Some Text'}";
    return new TriggerResponse { ResponseText = response };
}
Related