public class A { }
public class B:A { }
void foo()
{
A a = new B();
B b = a as B;
}
for a given instance setup, will lock(a) be equivalent to lock(b) ?
I mean, will locking be mutually exclusive? If I lock(a) in one thread and lock(b) in another thread, will I get a mutually exclusive access to that single instance of B created earlier?
Yes
lock(a){}is equivalent tolock(b){}.The lock() documentation states that the lock statement marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object of reference type.
aandbare both the same object so yes they are equivalent. Actuallyaandbare both references to the same object.A cast operation between reference types does not change the run-time type of the underlying object; it only changes the type of the value that is being used as a reference to that object. Source.
A quick test program shows that it does indeed behave the way it is documented: