Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot implicitly convert type void to object error in C#

Tags:

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#.

Result() will return the answer it gets from my Node.js server (FinalResponse) 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.

Error

cannot implicitly convert type void to object 

When I test the Lib.Result() 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 FinalResponse's value to returnedValue variable?

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("192.168.1.101:8000/mytest");
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader stream = new StreamReader(response.GetResponseStream());
    string FinalResponse = stream.ReadToEnd();
    Console.WriteLine(FinalResponse);
    }
  }  
}
like image 544
salep Avatar asked Nov 20 '16 18:11

salep


1 Answers

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("192.168.1.101:8000/mytest");

    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.

like image 159
Botond Balázs Avatar answered Sep 22 '22 15:09

Botond Balázs