| by Kenneth Chase | No comments

[C#] Properties & Accessors Tutorial with Examples | get, set & value keywords in C#


Hello Ace This is RetroTK2 and today you’ll learn all about properties in C# We’ll take a look at MSDN’s definition of a property Then we’ll look at some of the more primitive ways of accessing a private field After that, we’ll declare our very own property And finally, we’ll access that property If this is the first C# video your seeing, I’d strongly advise watching the series from the start… The card should be on your screen now And if you haven’t already, might I suggest downloading the channel-files that accompany this video The card should be on your screen once again So let’s get started… Well, what is a property? According to MSDN: “Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields” “Properties can be used as though they are public data members, but they are actually special methods called accessors.” “This enables data to be accessed easily while still providing the safety and flexibility of methods.” Let’s take a closer look at these things in action Open up Unity and create a basic C# script As always, make sure to give your script a different name than any other class in your project Here I’m going to create a very basic class Nothing too special here Ace, so feel free to call it whatever you like In the last C# video… the card is on your screen now in case you missed that Ace… We looked at fields in C# Here I’m defining a private ‘int’ field called “_myInt” Now a property is very similar to just defining a “get” and “set” method in your class to access the “_myInt” field So for example, I can define a ‘public’ method called “GetMyInt” with return type ‘int’ and simply return “_myInt” from it Like wise, I can define a ‘public’ method called “SetMyInt” with a ‘void’ return type that takes an int parameter and sets “_myInt” to that parameter’s value Ok let’s access our ‘getter’ and ‘setter’ methods in the “Tutorial14” class’s ‘Start’ method Create a new object from the class we just created and invoke both the “get” and “set” methods Now hey, you maybe thinking to yourself “that’s completely pointless and the same thing could be achieved by just making the ‘_myInt’ field public” and using it like so… Well yeah, that’s somewhat true Ace, but the real power of ‘getter’ and ‘setter’ methods is when you get the chance to preform other actions when the data is accessed For example, if I wanted to find out how many times “_myInt”‘s getter method was accessed, I could add a counter to the “GetMyInt” method and increment it each time it’s accessed Similarly, I could add some validation logic to the “SetMyInt” method to limit the value of “_myInt” to be between “1” and “4” I could also add a “Debug Log” to get the full call stack of where the “GetMyInt” method was called from A little bit out of the scope of this video Ace, so I’ll move on swiftly One slight disadvantage of this is that it’s not always clear what actions are being carried our when you try to access the data So say I call the “GetMyInt” method in my code, I really only expect to “Get My Int’s Value” I’m not expecting a counter to be incremented and I’m certainly not expecting a “Log” to occur You my want to bare that in mind when you’re using them in your code Ace, since it can get a little bit confusing You can also remove your ‘getter’ or ‘setter’ method altogether in order to limit the access to the “_myInt” field outside your class So say you only ever wanted people to read the value of “_myInt” and not be allowed to set that data… You could remove the “SetMyInt” method and deny them the ability to change the value outside your class Anyway, the wonderful coders at Microsoft felt that having to declare your ‘getter’ and ‘setter’ methods like this was a bit unnecessary… So they decided to create properties instead… Let’s create a property called “MyInt” Declaring a property is very similar to creating a field We start by giving the property an “Access Modifier”, ‘public’ in this case Then we give the property a ‘type’, which is going to be an ‘int’ And after that we declare the property’s name, which is “MyInt” All stuff that we’ve seen before Ace, nothing to different yet But now we’re going to mix things up a bit Open your curley braces… Oh yeah, we’re going off the rails now Ace Type in the “get” keyword… What is the “get” keyword? Well according to the Microsoft docs: “The get keyword defines an accessor method in a property or indexer that returns the property value or the indexer element.” After the ‘get’ keyword, open your curley braces once again Ace This is basically our “GetMyInt” method we defined earlier and it expects use to return an ‘int’ Here I am going to return the “_myInt” field Now to declare a “set” method, I type out the ‘set’ keyword… What is the “set” keyword? Well according to Microsoft docs: “The set keyword defines an accessor method in a property or indexer that assigns a value to the property or the indexer element.” I’m sure you never guessed that Ace Open your curly braces straight after it Here I want to set “_myInt” to the value passed to the ‘set’ accessor… But wait a second Ace, there’s no parameters being passed here Ah, you have to use the ‘value’ keyword What is the ‘value’ keyword? Well according to the Microsoft docs: “The contextual keyword value is used in the set accessor in ordinary property declarations.” “It is similar to an input parameter on a method.” “The word value references the value that client code is attempting to assign to the property.” So ‘value’ here takes the place of “myInt” parameter from the “SetMyInt” method Right let’s access our ‘get’ and ‘set’ accessors in the “Tutorial14” class’s ‘Start’ method If I type out “myClass” and hit full stop, you’ll see that our “MyInt” property can be accessed Which accessor is used depends on the way the property is accessed So if I logged out the “MyInt” property, the ‘get’ accessor will be called If I try to assign ’10’ to the “MyInt” property, the ‘set’ method is used So it works pretty much the way you would expect it to Ace The order of the ‘get’ and ‘set’ accessors don’t matter, so by all means put the ‘set’ above the ‘get’ if you like You can also add “Access Modifiers” to the ‘get’ and ‘set’ methods should you feel to need to limit their scope to just this class But be warned Ace, you can’t make them both private You could also just not declare them if you like, though doing so may cause a compiler error if you attempt to access the respective accessor Now creating a property like this is great and all, but having to create a private field and also having to declare the ‘get/set’ methods for the property is a real pain Well Ace, there is an even easier way to do it Here I’m creating a new property called ‘MyString’ that is of type ‘bool’… Nah, just kidding Ace, it’s a ‘string’ This time I open up my curly braces and type the ‘get’ keyword just like before… Except instead of opening my curly braces, this time I simply type out a semi-colon You’ll get an error, but if you do the same thing with the ‘set’ keyword, all should be fine This is an “Auto-Implemented Propety” Ace What is an Auto-Implemented Property? Well according to Microsoft docs: “In C# 3.0 and later” Unity uses C# 4 Ace “auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors.” “They also enable client code to create objects.” “When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property’s get and set accessors.” Auto-properties can also be prefixed with the ‘private’ “Access Modifier” Ace, but you can’t remove the ‘set’ or ‘get’ keywords both are required for the Auto property I’m afraid This has been a look at properties in C# And that’s it… Rate, Comment and Subscribe Ace, I hope you’re enjoying series 2 You can email me at [email protected] with the good news of the day Thank you for watching Ace, and I’ll see you in the next video

Leave a Reply