Handling optimistic concurrency violations I'm trying to establish a concurrency violation verification in my SQL updates using C# and raw SQL.

What I'm doing now is storing the TimeStamp value in a byte[] upon selection and before updating I'm checking if the stored value is equal to the current value. here's the code:

static void update()
{
    using (SqlConnection connection = new SqlConnection(""))
    {
        try
        {
            //open connection
            connection.Open();

            //select row for update - for testing purposes it's in the same block 
            SqlCommand select = connection.CreateCommand();
            select.CommandText = "SELECT timeStamp FROM Person WHERE ID = 1";
            //store the time stamp in a byte[]
            byte[] ts = (byte[])select.ExecuteScalar();

            //check if the time stamp hasn't changed
            if (ByteArraysEqual(ts, (byte[])select.ExecuteScalar()))
            {
                //Update
                SqlCommand command = connection.CreateCommand();
                command.CommandText = "Update Person SET Age=1111 WHERE ID = 1";
                command.ExecuteNonQuery();
            }
            else
            {
                //cocurrency violation occured
                Console.WriteLine("concurrency error!");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Update error:\n" + ex.Message);
        }
        finally
        {
            connection.Close();
        }
    }
}
static bool ByteArraysEqual(byte[] b1, byte[] b2)
{
    if (b1 == b2) return true;
    if (b1 == null || b2 == null) return false;
    if (b1.Length != b2.Length) return false;
    for (int i = 0; i &lt; b1.Length; i++)
    {
        if (b1[i] != b2[i]) return false;
    }
    return true;
}


I wonder if this is the right approach to verify the Person has not been updated by another user between the selection and the actual update?
What optimistic concurrency usually does is update the row specifying the old value in the where clause:

var command = connection.CreateCommand();
command.CommandText = "Update Person SET Age = @age timeStamp = @newTimeStamp WHERE ID = @id AND timeStamp = @originalTimeStamp";
command.Parameters.Add("@age", 1111);
command.Parameters.Add("@newTimeStamp", DateTime.Now);
command.Parameters.Add("@id", 1);
command.Parameters.Add("@originalTimeStamp", originalTimeStamp);
int affected = command.ExecuteNonQuery();

if (affected == 0)
{
    throw new OptimisticConcurrencyException("Data was changed by someone else, please refresh and try again");
}


Also, please use parameters for your SQL queries!