sender as in C# [duplicate]

An event’s sender is just passed to the event handler as an object. Now when that event is raised, you usually know what kind of sender you can expect (since you set up the event handler yourself), but the method still requires an object type.

Now the as is a type conversion that tries to convert the object into that type, but returns null if the type is not compatible. So in this case, you have this:

var rectangle = sender as Rectangle;

There are two possibilities:

  1. sender is a type that can be assigned to a Rectangle, in which case, rectangle will contain a reference to the same object but typed as a Rectangle instead of just object
  2. sender is of some other type, in which case rectangle will be null, which is caught in the following check.

Leave a Comment