In this lesson
- Use “var” to declare a variable
- Use explicit type declarations for a variable
- Intro to variable scope inside a class
Tap on time to skip ahead
Something you might see sometimes with C#, C# has this shorthand notation. When you instantiate a label, if you want to go ahead and set some of these props. I can say, “text=Hello World”, Background color = UIColor.Red. That basically replaces this here. When you write it like this, you think what’s the benefit of it? When you do it like this, you can do it all in one line of code.
Something else with C#, with C# you can specify a variable with just the var keyword. Another thing you can do is what’s known as explicit type. I just hit Alt Return and Xamarin Studio has given me this option where I can change that to specify the type of my variable. Some people like var, because their like “I’m already specifying the type here, it’s redundant to have it back over here.” But sometimes if you use explicit type like this, it’s more obvious about what’s going on.
Another nice thing I can do, I can hit Alt Return and I can assign this to a field which then brings it up at the class level. I can now reference this in other methods. If I didn’t do that, let’s rewind here, there is not hello label that I can reference here. If I go back and I make this the field, and then say this, we now know I have a reference to it.