I know that in C# using with braces is used to ensure that the object is disposed like the following:
using (MyResource myRes = new MyResource())
{
myRes.DoSomething();
}
Thus, this code is completely clear.
But I am reading a code where using with braces is used with anonymous instantiation. Here some samples:
public partial class FrmAuthenticate : Form
{
public String Username { get; set; }
public String Password { get; set; }
private void btnOk_Click(object sender, EventArgs e)
{
NetworkCredential writeCredentials = new NetworkCredential(txtUsername.Text, txtPassword.Text);
using (new NetworkConnection(IpPath, writeCredentials))
{
Username = txtUsername.Text;
Password = txtPassword.Text;
}
}
}
or
using (new NetworkConnection(TargetProgramSldDir, writeCredentials))
using (new NetworkConnection(@"\\"+ this.TargetServerIp, writeCredentials))
{
if (Directory.Exists(TargetProgramSldDir + @"\MyService"))
Copy(TargetProgramSldDir + @"\MyService", backupDir + @"\MyService");
}
How are the anonymous objects used in the two cases? How is the created object of NetworkConnection used in the two codes? I don't understand what the purpose of the using statement of especially the first sample code is?