Elevant Elevant - 2 months ago 7
C# Question

C# application exception void to string

I am really new to C# and i am trying to write a very basic scraper in a Console Appliciation however i get the error:

Cannot implicitly convert type void to string


What i am trying to do in the below code is set the returned input as a variable and return that variable to my Main method. so that the Main Method can access and read the returned value to be displayed if needed.

private static string setTargetModule()
{
string targetUrl = Console.Write("Target: http://");
return targetUrl;
}

Answer

The problem is that Console.Write("Target: http://") has does not return anything, since it is void.

To go around this, you will need to output the text onto the screen and then explicitely read it back. Thus, your code would become:

private static string setTargetModule()
{
    Console.Write("Target: http://");
    string targetUrl = Console.ReadLine();
    return targetUrl;
}

Or slightly shorter:

private static string setTargetModule()
{
    Console.Write("Target: http://");
    return Console.ReadLine();
}