Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I return an anonymous object in C# [duplicate]

My code returns an object:

  public async Task<IHttpActionResult> GetAnswers(int userTestQuestionId)
    {

  return Ok(new AnswerToClientDTO
        {
            AnswerGridCorrect = answerGridCorrect,
            Result = result,
            UpdateRowCount = updateRowCount
        });

Here is the code for the AnswerToClientDTO which is only used in the one place in my application:

public class AnswerToClientDTO
{
    public string AnswerGridCorrect { get; set; }
    public int UpdateRowCount { get; set; }
    public string Result { get; set; }
}

Is it possible for me to return an anonymous object where I do not have to declare a class from an ASP.NET WEb API method?

like image 638
Alan2 Avatar asked Dec 19 '22 07:12

Alan2


2 Answers

In WebAPI you can pass any object to Ok(), which can be formatted by a configured formatter, so this should be valid:

public IHttpActionResult GetStuff()
{
    return Ok( new {
        AnswerGridCorrect = answerGridCorrect,
        Result = result,
        UpdateRowCount = updateRowCount
    } );
}
like image 167
oxfn Avatar answered Jan 06 '23 01:01

oxfn


Technically, yes you can provided you use object or dynamic. That being said it is not a good idea. Also, if you are using this for a WebAPI like you mentioned (such as a REST or SOAP service via WCF) this would be a bad idea since the serialization from the HTTP call / to response won't know the proper formatting to use to send data back as JSON or XML.

like image 35
JNYRanger Avatar answered Jan 06 '23 00:01

JNYRanger