salep salep - 9 months ago 107
C# Question

cannot implicitly convert type void to object error in C#

I'm using this in an application where I am allowed to extend its functionality using my own code.

It's been coded in C#.

will return the answer it gets from my Node.js server (
) and I'm going to access it in the application like below, but I get the error in the title when I try to use EchoOut().

var returnedValue = Lib.Result();
App.EchoOut(returnedValue); // EchoOut allows you to test the function you wrote, it echoes string on the screen, but in this case, it gives an error.


cannot implicitly convert type void to object

When I test the
alone, I see the request is being made by the app, but I can't assign the returned value to a variable.

How can I assign the
value to

My code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace MainNameSpace
public class Lib
public void Result()
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string FinalResponse = stream.ReadToEnd();

Answer Source

You need to change the return type of the Result method to string and return the FinalResponse instead of writing it to the console.

public string Result() // <-- "string" instead of "void"
    var request = (HttpWebRequest)WebRequest.Create("");

    using (var response = (HttpWebResponse)request.GetResponse())
    using (var stream = response.GetResponseStream())
    using (var reader = new StreamReader(stream))
        return reader.ReadToEnd(); // <-- return the result

It is also considered good practice to wrap the code using disposable objects (in this case, objects of type HttpWebResponse, Stream and StreamReader) with using blocks.

I also took the liberty of using var instead of explicitly writing out the types of the variables because the types are already obvious from the right hand sides of the declarations.