Reputation:
I'm new to C# and trying to get my head around why the code below isn't working. I've tried to make a custom class HtmlRequest that isn't static so can be instantiated as many times as required using HtmlRequest someVar = new HtmlRequest();
return sb is holding the value but it's not being returned to hmtmlString
on the line htmlString = htmlReq.getHtml(uri)
.
I've tried putting Get{code ...return sb;} after public class HtmlRequest but can't get the correct syntax
public partial class MainWindow : DXWindow
{
private void GetLinks()
{
HtmlRequest htmlReq = new HtmlRequest();
Uri uri = new Uri("http://stackoverflow.com/");
StringBuilder htmlString = new StringBuilder();
htmlString = htmlReq.getHtml(uri); //nothing returned on htmlString
}
}
public class HtmlRequest
{
public StringBuilder getHtml(Uri uri)
{
// used to build entire input
StringBuilder sb = new StringBuilder();
// used on each read operation
byte[] buf = new byte[8192];
// prepare the web page we will be asking for
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
// execute the request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
Do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Encoding.ASCII.GetString(buf, 0, count);
// continue building the string
sb.Append(tempString);
}
}
while (count > 0); // any more data to read?
return sb;
}
}
If I put a breakpoint on return sb;
then the variable is correct but is not returning it.
It's probably something really obvious, can someone explain why it's not working and how to fix it?
Thank you
Upvotes: 0
Views: 137
Reputation: 50215
Try using the value instead of immediately exiting the method. An optimized build won't save the return value if it isn't used.
Upvotes: 1
Reputation: 16318
No need for this:
StringBuilder htmlString = new StringBuilder();
htmlString = htmlReq.getHtml(uri);
It's enough to say:
StringBuilder htmlString = htmlReq.getHtml(uri);
You'd have to define nothing. Nothing means "null", "garbage", what? Is htmlString the object it used to be? Or maybe the function does not return at all? What is it?
Upvotes: 1