-3

this is a piece of code from a register app which uses databases.Since i can say i know the basic principles of OOP , I understand this code EXCEPT FOR THE FIRST LINE. How can an object (reader) be a method(ExecuteReader()) of another object (cmd1) from another class(SqlCommand)? I expected that the only way i can create an object is by writing sth like this: (class object = new class()). A link where this to be explained would be welcomed too.

using(SqlDataReader reader = cmd1.ExecuteReader())
{
    if (reader.Read())
    {
        reader.Close();
        if (textBox4.Text == textBox5.Text)
        {
            using (SqlCommand cmd = new SqlCommand("UPDATE info SET Password=@Password WHERE Id=@Id AND Password=@Password1", conn))
            {
                cmd.Parameters.AddWithValue("@Password", textBox4.Text);
                cmd.Parameters.AddWithValue("@Id", textBox3.Text);
                cmd.Parameters.AddWithValue("@Password1", textBox2.Text);
                cmd.ExecuteNonQuery();
            }
            MessageBox.Show("Password has been changed");
        }
        else
            MessageBox.Show("The new password doesn't match the one written in repeat the new password blank space ");
    }
    else
        MessageBox.Show("Wrong Id or Password");
}
Rob
  • 26,989
  • 16
  • 82
  • 98
Lazu Razvan
  • 49
  • 2
  • 8
  • 3
    You know how methods can return a value, like an int or a string? They can return instances of objects, too. `ExecuteReader` returns an instance of a `SqlReader` object. the `using` block uses the object then once the block finishes it gets rid of the object. – sab669 Aug 28 '15 at 12:19
  • Methods can return objects. It would be pretty difficult to write an object oriented system if every return type had to be `void`. – David Aug 28 '15 at 12:21

3 Answers3

0

Here method call cmd1.ExecuteReader() returns an instance of object of type SqlDataReader.

Then reference to this object is being assigned to the variable reader of the same type SqlDataReader.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
0

reader is not a method, it is the object returned by the function ExecuteReader.

ExecuteReader will create an object with the usual syntax new SqlDataReader(...) and then return it. That's all !

Chostakovitch
  • 965
  • 1
  • 9
  • 33
0

Imagine a greatly simplified version of that method doing something like this:

public SqlDataReader ExecuteReader() 
{
    return new SqlDataReader();
}

Obviously the implementation is more complex than this, but you can easily see how a method call can return you an object.

Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138