2

So im trying to learn c# because i want to change my old programming skill which is vb.net im opening some converter site but it doesn't work. I just want to know the code of USING and WITH in vb.net to c#.

here's my code in vb.net:

Dim rand As New Random
    abuildnumber.Text = rand.Next
    Dim exist As String = String.Empty
    exist &= "select * from stocks "
    exist &= "where build_number=@build"
    Using conn As New SqlConnection("server=WIN10;user=admin;password=12345;database=pc_parts")
        Using cmd As New SqlCommand
            With cmd
                .Connection = conn
                .CommandType = CommandType.Text
                .CommandText = exist
                .Parameters.AddWithValue("@build", abuildnumber.Text)
            End With
            Try
                conn.Open()
                Dim reader As SqlDataReader = cmd.ExecuteReader
                If reader.HasRows Then
                    reader.Close()
                    abuildnumber.Text = rand.Next
                End If
                abrand.Enabled = True
                apart.Enabled = True
                aquantity.Enabled = True
                aday.Enabled = True
                amonth.Enabled = True
                ayear.Enabled = True
                add.Enabled = True
                conn.Close()
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End Using
    End Using
End Sub
Md. Suman Kabir
  • 5,243
  • 5
  • 25
  • 43
Ndrangheta
  • 39
  • 5
  • 2
    Possible duplicate of [Equivalence of "With...End With" in C#?](https://stackoverflow.com/questions/1063429/equivalence-of-with-end-with-in-c) – Magnetron Nov 30 '17 at 15:17

2 Answers2

3

In C# the using is pretty much the same syntax:

// Notice single lined, or multi lined using statements { }
using (var conn = new SqlConnection("server=WIN10;user=admin;password=12345;database=pc_parts"))
  using (var cmd = new SqlCommand())  
  {

  }

Thankfully, there's no With equivalent in C#

reckface
  • 5,678
  • 4
  • 36
  • 62
2

The using syntax is very similar:

using (conn As new SqlConnection("server=WIN10;user=admin;password=12345;database=pc_parts"))
{
    // some code here
}

I'm not sure there is a straight-up way to do what you are doing with "With". Though, you can inline assignments into your object declaration like this:

cmd = new SqlCommand {
    Connection = conn,
    CommandType = CommandType.Text,
    CommandText = exist
};
cmd.Parameters.AddWithValue("@build", abuildnumber.Text);
snow_FFFFFF
  • 3,235
  • 17
  • 29