I don't understand this code.

I have a question about a line of code. I was looking at some code on how to implement ftp in .net 2.0 and saw this line of code.



response = (FtpWebResponse)request.GetResponse();

my question is, why is FtpWebResponse in parenthisies?
Usually you only see parenthisies when you use a method and place the arguments within them, if there are any.

I also have a question about another line of code regarding the using statement. This next line of code is right below the previous line of code in the source code I was looking at.



using (StreamWriter sw0=File.AppendText(log_path_success))
{
sw0.WriteLine(fileInfo.Name);
}

I thought that the using statement was only for including namespaces into the code. Can you please give an explination and/or references regarding these two statements?

Thanks!

-Mike

[1303 byte] By [MikeF] at [2008-2-20]
# 1
Mike F wrote:

my question is, why is FtpWebResponse in parenthisies?

It is called a "cast". GetResponse() is declared to return an object of type WebResponse. However, we know that when accessing an FTP URL, it will really return an object of type FtpWebResponse. This is allowed because FtpWebResponse derives from WebResponse.


I thought that the using statement was only for including namespaces into the code.

using also has another meaning in C#: It can be used to ensure that resources are disposed of in a timely fashion.

.NET defines an interface called IDisposable, which has a single method, Dispose(). Types that implement IDisposable use the Dispose() method to close handles, get rid of various resources, etc.

The using statement works in conjunction with IDisposable. You could use IDisposable types like this:

[code language="c#]
Resource res = new Resource()
try
{
res.Use();
}
finally
{
res.Dispose();
}
[/code]

However, the using statement lets you do the same thing in a simpler way:
[code language="c#"]
using( Resource res = new Resource() )
{
res.Use();
} // res.Dispose() called here

ArildFines at 2007-9-8 > top of Msdn Tech,Visual C#,Visual C# Language...
# 2
Ah, thanks for clearing that up Arild! Your explination on casting was a little confusing but now knowing that usage is called casting I was able to get a good explination on this page:
http://msdn2.microsoft.com/library/ms173105(en-us,vs.80).aspx
MikeF at 2007-9-8 > top of Msdn Tech,Visual C#,Visual C# Language...