Xamarin.iOS – Casting Objects with C#

In this lesson

  • Casting with “as”
  • Casting with ()


Tap on time to skip ahead


This part of the text, it’s just sending a generic object. “Here’s something, we don’t know what it is, it’s just something.” Because we’re the programmers, we know what was set up, we know it’s a UIButton. But to be able to set the title, I can’t say, “sender.settitle” because the compiler doesn’t know what sender is yet. By specifying sender as UIButton, we’re telling the compiler, “Hey, in this particular instance the sender is UIButton.” The “as” keyword is more or less for the compiler to take something that’s generic and attempt to do casting to make it what it really is.


Another way of casting things in C# is you can put this here. If sender is not the UIButton, it will throw an exception right here. The difference with as, is if I say as UIButton, and it isn’t a UIButton, it just creates a null and then it’s going to throw an error when I try to set title on something that is null or doesn’t exist.


Let’s say we had a method that accepted a generic object and it has to do different things based on the type of that generic method. You can use “as” as a way to figure out if something is a UIButton or not.


For example, here’s how you would actually use it. I would say, “button = sender as UIButton.” I can say, “if sender doesn’t = null then do this like that.” Then I can also say “var text field = sender as UILabel if tf doesn’t = null.” You get the idea.


There’s definitely times, method wise, if you just have a regular function or method that handles a generic object where this might come in useful. A lot of times, I’ve done something similar when I’m dealing with notifications that iOS might send my application.