The
as
operator checks the given object and if it can be converted to the given type returns it as that type. Otherwise, it returns
null
. It's used when you don't know what type of value is being passed into a method (often an event handler) and you need to check so that you don't cause problems by trying to use it as a type it isn't:
For example:
ListBox lb = new ListBox();
...
Control c = lb;
...
TextBox tb = c as TextBox;
will give
tb/code> as <code>null
becasue a ListBox cannot be converted into a Textbox, whereas
TextBox tb = new TextBox();
...
Control c = tb;
...
TextBox tb2 = c as TextBox;
will give tb2 as a TextBox instance.
It's a safe way of checking the type without potentially causing a type casting exception if the conversion cannot be made.
The second line subtracts two property (or field) values and returns the result to the calling method.