C# Properties: Why use "get" and "set"
HTML-код
- Опубликовано: 26 авг 2024
- I'm learning C# and thought I might share how properties started to make sense to me.
Based on SoloLearn Properties Lesson
Final Code from video is available here: code.sololearn...
and can be edited live.
I lost 3 hours with another videos before..but your explanations are concise and understandable. thanksssssssss! :D
I like your profile pic. it's very relaxing and happy!
Frick'n Genius. I kept tossing this around in my head knowing i was making it more complicated than it was. The book gave 2 examples and moved on. Thanks for getting me pass the wall.
This is well explained.
So properties are basically fancy wrappers for variables in a class. In the same way that a class can have variables you can read and write to, you can read and write to a property of that class.
The difference is that any property you define within the class will have, syntactically, a "get" code block { xxx } (for reading) and a "set" code block { xxx} (for writing), where the xxx are lines of code. What the property 'gets' and 'sets' from is actually a variable within the class that you specify.
This sounds just like a normal variable, but within those curly brackets { xxx } you can have some logic. For example you may only want to set new values if they are positive.
For example, inside the get {xxx} code block you would probably just want to return the value of the property. If that is the case just write [ get { return backingfield; } ]
And similarly inside the set {xxx} code block you could just write [ set { backingfield = value } ] where value is whatever you are trying to set the property to.
In the immediate example above the property is functionally identical to a variable, but the real power of the property is the logic you can use when getting and setting the backing field. (the backing field is a variable within the class of property that you are actually writing and reading from, remember the property is only a wrapper for this variable).
So basically
private string _name;
// This is the variable
public string Name
// This is the property (wrapper for a variable)
{
get { return _name;
} // This is called whenever we do print(Name)
set { _name = value;
} // This is called whenever we do Name = 5. Note that *value* is whatever we are trying to set the property to, it is automatically replaced with a value on execution.
}
In some sense properties are just fancy public ways to access private variables.
Of course in the code above _name is our "backing field", an actual variable that the property is wrapping around. However it's not necessary to initalize a backing variable and reference it in the property. ie, we don't have to have a backing field at all.
Sometimes it's common to see
public string Name {get; set;} hiddenvalue;
set => hiddenvalue = value;
}
The '=>' is called the lambda operator which means "given the left, return the right", ie when get is called return hiddenvalue, and when set is called return the value of hiddenvalue which we set to value. It's functionally equivalent to the code further above.
The interesting part of the code is how hiddenvalue comes out of nowhere. When you do {get; set}, the compiler basically attaches a hidden backing field/ ghost variable to the property. It's there, you just don't see it. Of course there is no actual 'hiddenvalue' variable you can access, but any code reading/writing to the property will work as you would expect, as if you manually attached a variable to the property like in the examples in the video.
based ty
Thank you, that was exactly the explanation we needed. Coding education needs more like this
Yeah just finished a C# class where the teacher just said what the description of get set is by microsoft. Had no idea of its uses. After seeing this he could easily say "You use get and set to better control your properties through if statements if needed". That would explain it! Damnit
this makes much more sense. i couldn't understand why people needed to use gets and sets and didn't see a reason to use the get and set property.
at least now i understand.
Excellent vid Tom - almost 5 years to the day you posted this video, it helped me complete my knowledge of G&S - thank you!
Tom - I'm learning C# and your example absolutely cleared things up for me. I deeply appreciate it.
Wow - I was not understanding properties and get/set at all - but your video was great. I get it now - This was fantastic - thanks a lot for sharing!
Thanks for the help, I have been stuck on this subject for quite a while!
holly molly your explanation was so good that i understood setter and getter in 14 mins! thanks a lot! god bless you!
Holly and Molly are girls' names. You meant "Holy moly". It's just funny
Man thaaaaaaanks A LOT!!! i have been thinking about this for days till at last i watched your video thanks
Well done man.
Wish you did more such videos because it felt like you know the exact details which us beginners struggle to gets(no pun intended). Your tone along with your pace was perfect for me to get and set
Normally I don't comment on videos but this was spot on, much appreciated. Coming from a Python background this is new to me and I didn't feel like reading 6 pages of text to understand something you could show me in 10 minutes. Tip of the hat to ya.
I came here from learn.unity which I was lost. Now i get it thank you so much!
The naming convention also says that private data members should have their name start with '_' so >> _age should be the name.
good thing I scrolled down before I clicked off the video lol - cheers mate
Best explanation so far by a long shot. Thanks.
Dude thank you so much for sharing. I was so confused about get and set! But your explanation makes so much sense. Thank you for clearing up so much confusion.
Thanks, This was a big help in understanding. My textbook doesn't delve into the 'why' as much as I would like.
thanks for sharing ! , i wish you share more videos
Excellent Explanation! Thanks!
Thank you so much. Exactly what I was looking for.
just want to say, visual studio, at least for me seems a lot faster to see, correct and show errors as you learn. and it's free
Thank you, you made it very clear. I finally understand the sololean lesson x)
Thanks man, I'm also learning C# .Xaml MySQL HTML and CSS at uni, i'm a second year who gets A's, this will help me for my Assignment which is a cross-platform app database (Y)
I found this useful and thought u would like to know that.
Cheers!
Tom. I’m telling you man... they need to explain real world applications of these teachings! I know how to code but I have no idea how to properly code!
very helpful understanding much better
great explanations to be new at this. Other videos over complicate it
Tom, thanks for the video. Unfortunately the resolution was so bad I couldn't even read some of the text, especially the red text. Did you upload the video with low resolution. I did consider the issue may be on my side but other videos are clear. Thanks anyway.
Is it okay to use public variables for static classes without getters and setters? I get why use setters and getters for structs and dynamic classes, but I barely need them, and I thought it's a security thing, for say, if someone was reverse engineering my program or something like that -- if setters aren't a security thing, then I sure as heck don't need 'em often.
So essentially properties are useful for class properties that need abit of control?
Like the age example with the boundaries of below 0? or the gender example with only 2 options available?
Appreciate your effort,you made it preety clear.
Great video, clear and understandable presentation - helped me immensely, thanks!
Simply great Thank you man
Just a general thing about data....keeping age in the program or database is kinda weird, unless you die it is changing all the time. If you keep a birthdate, normally that won't change. Age is more a computed thing like current date - birth date. This isn't specific to today's topic tho.
Also, I am fine with the get and set taking and returning something different than the backing field, but I feel there should be parity between them, i.e. if you are going to return hands / 5 for Hands on a get, wouldn't you want to set hands to Hands * 5 on a set? Just something to think about. It's like if you were working internally in Celsius but get and set did Fahrenheit.
Thanks, Tom, you're the best.
Good job
i would recommend downloading Visual Studios (Newest) (FREE) Also download Xamarin, this is all C# based mate and cross-platform apps can be built to a high spec...
Also CocosSharp Xamarin is free with Visual Studios for mono games... and again C# oriented (CCsharp have their own syntax but its easy as ****)
Thanks!
Upvoted!
not sure if you used "value", but im at that part of the video (i'll keep watching though). i have no clue what your "value" is supposed to be.
Thanks
Fantastic! Thank you so much!
Greatly explained!!
Awesome explanation.
Thanks!
8:20 why wouldn't you just use a method to control the inputs?
thanks cupcake
Great explanation!
thanks
Well done. Thanks!
nice explanation, but i have one question. why the value = 0 when the user puts a negative age? age = value in the if, but what is the value of the value?
value is a keyword that takes the value of the input : docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/value
here the input of Age was -234 so the set{} actually didn't do anything, 0 was the default value of age
thank you that was great explanation ..
Hey Tom, how is learning coming along? Curious how the Solo Learn helped you.
S B hey, I haven’t used Solo Learn in quite awhile but I found it very helpful to quickly get familiar with syntax and basic concepts. I find the best learning to take place when you start to actually code.
Great video man!
Thanks a lot:)
Is solo learn basically the same as the .NET framework on visual studio?
i dont understand what Get does help
nice for a beginner
Great explanations! But, I am stuck with the following, what is so special with fields that it should be kept private and why properties is no problem to access it? If you can change the value of a property trough set, then why not make the field public? I don't see the difference..
For one thing you can ensure that the value it is set to makes some sense. There are other reasons but that is the simplest and most common and straightforward. He shows an example of this about 6:30 in.
@@jvsnyc thanks yeah i now know why at the time it was not clear for me. the main reason i see is through property you can add control checks before assiging it blindly to the field (variable) this will enhanche the integrity of the program. for instance for the variable field you can add a control through if statement that it should not accept a negative number. actually the problem in understanding this concept is because we don't use this in the normal variable declaration ..which in fact would also be a good habit to do ..but this will slow down the programming and for the ease of simplicity we just leave it out.
Thank you Sir!
This was helpful. Thanks..!!
Awesome man
Thank You!
I have a question. Is there any advantage to using this { get; set; } syntax over doing it the old fashioned OOP way (having Set() and Get() methods and encapsulizing the code)???
Is the only advantage just the shorter code or there is an actual performance advantage or use case advantage?
I'd appreciate any input!
VEGETADTX shhhhh
@@HaynesX Ok, I guess I said "I'd appreciate ANY input" after all :) But I still wonder and wish someone could answer me :)
@@sixtenklementsson Dammit! Will someone seriously answer my question I genuinely wonder :D
Have you learned programming using Sololearn website ?
So it's just a fancy way of variable affecting. you can just set conditions and all that without properties.
man I could never get this into my head
It's probably to keep the code clean, that the conditioning and all the variable's supervision is in that class' folder itself instead of the actual code
well thank you i can understand its usage but why would we use it that i do not understand !?
we still can do all these things in public and without set or get !
With Get And Set property you can Choose and control what to do when a person is accessing your class´s information. Without it, they can just access it, with it , you have complete control and can even condition the access to the variable.
@@alanvargas3148 Much obliged
@@amjad.m479 what does that mean?
@@alanvargas3148 it means thank you
thank you it really helped me😁😁
that was helpful :D, thanks dude.
you can use bool for gender
nevermind you made a check for male female ;D
Couldn't you write the hands part like:
```public int Fingers{
get{return hands*5}
set{hands = value}
}```
that should make more sense reading it. 'Cause when you call Tom.Hands vs Tom.Fingers ..getting 10 make more sense with the second.
or is it not possible to set the lower case hand variable to 2. You'd have to assign the number of hands with Tom.Fingers = 2; which again make no sense i guess.
Is this object orientated programming?
Yes
Awesome explanation. It _is_ just like in Java, purely as "vanilla" getter/setter ({ get; set; }) it's pretty much useless noise code.
based 10:00
You look older than 30 dude! I'm just kidding! ;) So basically "get" and "set" are used to disclose the private classes? What if you only use return and just set them? I suppose that it is not gonna work right?
Haven't you heard???? You can be any gender you can come up with!!! Even if it doesn't exist! Hahaha
Bahahahahaaaaa 11:05 I was literally thinking you should use something stupid like "blue" for gender. XD so weird that you used exactly that!!
private string gender = "attack helicopter";
A L I E N S x) beautiful
None of this made sense until he did hands lol
you talk like its a Gundam, he has a youtube channel. *It'sAGundam*
there's nothing complicated ! you just use filtering on your data in order to avoid possible wrong input by the outer users.
Your CPU must be so expensive
no the site is just super freaking slow, I thought it was my computer too
this exactly the same as Brackeys, didn't even try to change the exemple character name ? Come on ^^'
I'm not sure what you mean by your comment... are you saying the IDE looks similar to Brackets?
tom, brackeys is another c# channel his claiming you stole their work
stannis Barracuda ah thanks for the clarification... actually kind of honored to think it was copied, but just made this up on the go based on Solo Learn. In terms of the name... my name is Tom, and age was 30 at the time :)
thanks