C# Properties: Why use "get" and "set"

  Рет қаралды 66,352

Tom McCurdy

Tom McCurdy

7 жыл бұрын

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.com/c1IMnuYG7M...
and can be edited live.

Пікірлер: 107
@maria-alexandra2253
@maria-alexandra2253 6 жыл бұрын
I lost 3 hours with another videos before..but your explanations are concise and understandable. thanksssssssss! :D
@lukashenrique4295
@lukashenrique4295 3 жыл бұрын
I like your profile pic. it's very relaxing and happy!
@emelioherrera5080
@emelioherrera5080 6 жыл бұрын
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.
@bobsagget823
@bobsagget823 5 жыл бұрын
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.
@BrentMalice
@BrentMalice 8 ай бұрын
based ty
@davidacosta6383
@davidacosta6383 6 жыл бұрын
Thank you, that was exactly the explanation we needed. Coding education needs more like this
@Avean
@Avean 6 жыл бұрын
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
@Dexterroberson
@Dexterroberson 6 жыл бұрын
Tom - I'm learning C# and your example absolutely cleared things up for me. I deeply appreciate it.
@clifton200124
@clifton200124 3 жыл бұрын
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.
@willh69
@willh69 2 жыл бұрын
Excellent vid Tom - almost 5 years to the day you posted this video, it helped me complete my knowledge of G&S - thank you!
@amirhosseinkhodami762
@amirhosseinkhodami762 6 жыл бұрын
Man thaaaaaaanks A LOT!!! i have been thinking about this for days till at last i watched your video thanks
@SlayerPrincess
@SlayerPrincess 5 жыл бұрын
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.
@rkeshat3014
@rkeshat3014 2 жыл бұрын
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
@ElseIfGambit
@ElseIfGambit 2 жыл бұрын
Thanks for the help, I have been stuck on this subject for quite a while!
@vincelobuzzetta352
@vincelobuzzetta352 4 жыл бұрын
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!
@gabrielgilliam6888
@gabrielgilliam6888 4 жыл бұрын
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.
@b3armonk
@b3armonk 3 жыл бұрын
I came here from learn.unity which I was lost. Now i get it thank you so much!
@jessievalladares
@jessievalladares 7 жыл бұрын
Excellent Explanation! Thanks!
@jimmyjobindi2128
@jimmyjobindi2128 4 жыл бұрын
Best explanation so far by a long shot. Thanks.
@Hawkadium
@Hawkadium 4 жыл бұрын
Thank you so much. Exactly what I was looking for.
@wolflover5793
@wolflover5793 5 жыл бұрын
holly molly your explanation was so good that i understood setter and getter in 14 mins! thanks a lot! god bless you!
@francisluglio6611
@francisluglio6611 4 жыл бұрын
Holly and Molly are girls' names. You meant "Holy moly". It's just funny
@luciechuard6590
@luciechuard6590 5 жыл бұрын
Thank you, you made it very clear. I finally understand the sololean lesson x)
@DeanPickersgill
@DeanPickersgill 5 жыл бұрын
Great video, clear and understandable presentation - helped me immensely, thanks!
@manshellramos1292
@manshellramos1292 5 жыл бұрын
Thanks,​ Tom, you're the best.
@shanuchandra7156
@shanuchandra7156 6 жыл бұрын
Simply great Thank you man
@Mesdiyt
@Mesdiyt 4 жыл бұрын
Appreciate your effort,you made it preety clear.
@BaronVonTacocat
@BaronVonTacocat 6 жыл бұрын
Awesome explanation. Thanks!
@user-qk4tx9jc4m
@user-qk4tx9jc4m 5 жыл бұрын
Greatly explained!!
@sanakabbani2865
@sanakabbani2865 4 жыл бұрын
thanks for sharing ! , i wish you share more videos
@kurtgalvin
@kurtgalvin 4 жыл бұрын
Great video man!
@Caltuit
@Caltuit 5 жыл бұрын
Great explanation!
@jonathaningersoll6213
@jonathaningersoll6213 4 жыл бұрын
Fantastic! Thank you so much!
@ricks341
@ricks341 6 жыл бұрын
Well done. Thanks!
@phillbon3457
@phillbon3457 5 жыл бұрын
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!
@amanshukla6500
@amanshukla6500 3 жыл бұрын
The naming convention also says that private data members should have their name start with '_' so >> _age should be the name.
@willh69
@willh69 2 жыл бұрын
good thing I scrolled down before I clicked off the video lol - cheers mate
@Scxe
@Scxe 5 жыл бұрын
Thanks, This was a big help in understanding. My textbook doesn't delve into the 'why' as much as I would like.
@AnasJayyusi
@AnasJayyusi 6 жыл бұрын
thank you that was great explanation ..
@Kenken-eb5qg
@Kenken-eb5qg 4 жыл бұрын
Thank you Sir!
@adilarhrimaz2606
@adilarhrimaz2606 5 жыл бұрын
that was helpful :D, thanks dude.
@user-mx1ds5mf3i
@user-mx1ds5mf3i 6 жыл бұрын
Thanks a lot:)
@bx6p166
@bx6p166 3 жыл бұрын
very helpful understanding much better
@birajdarvinay95
@birajdarvinay95 4 жыл бұрын
This was helpful. Thanks..!!
@arturlaherand8840
@arturlaherand8840 4 жыл бұрын
Thank You!
@keithscott9774
@keithscott9774 5 жыл бұрын
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.
@thetravelingraf
@thetravelingraf 5 жыл бұрын
Awesome man
@user-qf1oz9ze6z
@user-qf1oz9ze6z 5 жыл бұрын
thank you it really helped me😁😁
@kailashviswanathan250
@kailashviswanathan250 4 жыл бұрын
Upvoted!
@Paul-zr4iw
@Paul-zr4iw 4 жыл бұрын
Good job
@uriel5899
@uriel5899 4 жыл бұрын
Thanks
@manuelillanes1635
@manuelillanes1635 4 жыл бұрын
thanks
@ivangutowski
@ivangutowski 3 жыл бұрын
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
@benlee5039
@benlee5039 6 жыл бұрын
Is solo learn basically the same as the .NET framework on visual studio?
@alexjulius69
@alexjulius69 2 жыл бұрын
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.
@sagiv3106
@sagiv3106 3 жыл бұрын
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?
@tomsawyer1799
@tomsawyer1799 5 жыл бұрын
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!
@jvsnyc
@jvsnyc 5 жыл бұрын
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.
@phillbon3457
@phillbon3457 5 жыл бұрын
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!
@kerolesmonsef4179
@kerolesmonsef4179 5 жыл бұрын
nice for a beginner
@VEGETADTX
@VEGETADTX 5 жыл бұрын
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!
@HaynesX
@HaynesX 5 жыл бұрын
VEGETADTX shhhhh
@VEGETADTX
@VEGETADTX 5 жыл бұрын
@@HaynesX Ok, I guess I said "I'd appreciate ANY input" after all :) But I still wonder and wish someone could answer me :)
@VEGETADTX
@VEGETADTX 5 жыл бұрын
@@sixtenklementsson Dammit! Will someone seriously answer my question I genuinely wonder :D
@Scott.B70
@Scott.B70 5 жыл бұрын
Hey Tom, how is learning coming along? Curious how the Solo Learn helped you.
@b0otable
@b0otable 5 жыл бұрын
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.
@salemuae127
@salemuae127 6 жыл бұрын
Have you learned programming using Sololearn website ?
@21agdmnm
@21agdmnm 5 жыл бұрын
thanks cupcake
@Layarion
@Layarion 6 жыл бұрын
8:20 why wouldn't you just use a method to control the inputs?
@Danyu91
@Danyu91 4 жыл бұрын
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.
@heysuckers1234
@heysuckers1234 5 жыл бұрын
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?
@Ne3zyTV
@Ne3zyTV 5 жыл бұрын
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
@FLiKEDD
@FLiKEDD 4 жыл бұрын
you can use bool for gender
@FLiKEDD
@FLiKEDD 4 жыл бұрын
nevermind you made a check for male female ;D
@confidential303
@confidential303 5 жыл бұрын
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..
@jvsnyc
@jvsnyc 5 жыл бұрын
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.
@confidential303
@confidential303 5 жыл бұрын
@@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.
@unberyl
@unberyl 4 жыл бұрын
Awesome explanation. It _is_ just like in Java, purely as "vanilla" getter/setter ({ get; set; }) it's pretty much useless noise code.
@mohdasyraf999
@mohdasyraf999 3 жыл бұрын
i dont understand what Get does help
@golden4593
@golden4593 4 жыл бұрын
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
@sagiv3106
@sagiv3106 3 жыл бұрын
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
@amjad.m479
@amjad.m479 4 жыл бұрын
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 !
@alanvargas3148
@alanvargas3148 4 жыл бұрын
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.
@amjad.m479
@amjad.m479 4 жыл бұрын
@@alanvargas3148 Much obliged
@alanvargas3148
@alanvargas3148 4 жыл бұрын
@@amjad.m479 what does that mean?
@amjad.m479
@amjad.m479 4 жыл бұрын
@@alanvargas3148 it means thank you
@RajenParekh13
@RajenParekh13 7 жыл бұрын
Is this object orientated programming?
@Lakelets
@Lakelets 6 жыл бұрын
Yes
@joseluizdurigon8893
@joseluizdurigon8893 2 жыл бұрын
based 10:00
@SlayPlenty
@SlayPlenty 2 жыл бұрын
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.
@legittaco4440
@legittaco4440 3 жыл бұрын
None of this made sense until he did hands lol
@JobQuestUnveiled
@JobQuestUnveiled 7 жыл бұрын
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?
@xydoublehelix2924
@xydoublehelix2924 5 жыл бұрын
you talk like its a Gundam, he has a youtube channel. *It'sAGundam*
@FacePalmProduxtnsFPP
@FacePalmProduxtnsFPP 6 жыл бұрын
Haven't you heard???? You can be any gender you can come up with!!! Even if it doesn't exist! Hahaha
@FacePalmProduxtnsFPP
@FacePalmProduxtnsFPP 6 жыл бұрын
Bahahahahaaaaa 11:05 I was literally thinking you should use something stupid like "blue" for gender. XD so weird that you used exactly that!!
@aliens5142
@aliens5142 6 жыл бұрын
private string gender = "attack helicopter";
@FacePalmProduxtnsFPP
@FacePalmProduxtnsFPP 6 жыл бұрын
A L I E N S x) beautiful
@egeucoklar1410
@egeucoklar1410 6 жыл бұрын
there's nothing complicated ! you just use filtering on your data in order to avoid possible wrong input by the outer users.
@elliot6855
@elliot6855 6 жыл бұрын
Your CPU must be so expensive
@hobbiesandhustles
@hobbiesandhustles 5 жыл бұрын
no the site is just super freaking slow, I thought it was my computer too
@remiscovolo3313
@remiscovolo3313 6 жыл бұрын
this exactly the same as Brackeys, didn't even try to change the exemple character name ? Come on ^^'
@b0otable
@b0otable 6 жыл бұрын
I'm not sure what you mean by your comment... are you saying the IDE looks similar to Brackets?
@stannisbarracuda5693
@stannisbarracuda5693 6 жыл бұрын
tom, brackeys is another c# channel his claiming you stole their work
@b0otable
@b0otable 6 жыл бұрын
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 :)
@a2319743
@a2319743 5 жыл бұрын
thanks
C# Tutorial: Properties, Getters and Setters
11:39
Ian Schoenrock
Рет қаралды 26 М.
C#: Static vs Non-Static: SoloLearn Connar's Static Member Question
17:09
Red❤️+Green💚=
00:38
ISSEI / いっせい
Рет қаралды 64 МЛН
Did you believe it was real? #tiktok
00:25
Анастасия Тарасова
Рет қаралды 56 МЛН
Object-Oriented Programming is Embarrassing: 4 Short Examples
28:03
13. How to program in C# - PROPERTIES - Beginner Tutorial
18:33
Understand your C# queries! IEnumerable & IQueryable in explained
11:28
tutorialsEU - C#
Рет қаралды 32 М.
Learn C# for beginners: 54 -  Get and Set Methods
16:44
Jesse Dietrichson
Рет қаралды 30 М.
C# getters & setters 🔒
4:06
Bro Code
Рет қаралды 143 М.
C#: Very Basic Indexers Example + Sample Code
11:26
Tom McCurdy
Рет қаралды 1,9 М.
Top 10 C# Best Practices (plus bonuses)
57:28
IAmTimCorey
Рет қаралды 509 М.
C# Tutorial for Beginners 23 : Classes Part 3 Getters & Setters
13:30
JackedProgrammer
Рет қаралды 1,4 М.
Samsung Galaxy Unpacked July 2024: Official Replay
1:8:53
Samsung
Рет қаралды 23 МЛН
Красиво, но телефон жаль
0:32
Бесполезные Новости
Рет қаралды 963 М.
iPhone 15 Pro в реальной жизни
24:07
HUDAKOV
Рет қаралды 345 М.