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.

Комментарии • 108

  • @maria-alexandra2253
    @maria-alexandra2253 7 лет назад +31

    I lost 3 hours with another videos before..but your explanations are concise and understandable. thanksssssssss! :D

    • @lukashenrique4295
      @lukashenrique4295 3 года назад +1

      I like your profile pic. it's very relaxing and happy!

  • @emelioherrera5080
    @emelioherrera5080 6 лет назад +7

    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 лет назад +10

    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.

  • @davidacosta6383
    @davidacosta6383 6 лет назад +12

    Thank you, that was exactly the explanation we needed. Coding education needs more like this

    • @Avean
      @Avean 6 лет назад +1

      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

  • @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!

  • @Dexterroberson
    @Dexterroberson 6 лет назад +1

    Tom - I'm learning C# and your example absolutely cleared things up for me. I deeply appreciate it.

  • @vincelobuzzetta352
    @vincelobuzzetta352 4 года назад +1

    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!

  • @ElseIfGambit
    @ElseIfGambit 2 года назад

    Thanks for the help, I have been stuck on this subject for quite a while!

  • @wolflover5793
    @wolflover5793 5 лет назад +1

    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

  • @amirhosseinkhodami762
    @amirhosseinkhodami762 7 лет назад +12

    Man thaaaaaaanks A LOT!!! i have been thinking about this for days till at last i watched your video thanks

  • @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

  • @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!

  • @amanshukla6500
    @amanshukla6500 3 года назад +1

    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

  • @jimmyjobindi2128
    @jimmyjobindi2128 4 года назад

    Best explanation so far by a long shot. 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.

  • @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.

  • @sanakabbani2865
    @sanakabbani2865 4 года назад +1

    thanks for sharing ! , i wish you share more videos

  • @jessievalladares
    @jessievalladares 7 лет назад +7

    Excellent Explanation! Thanks!

  • @Hawkadium
    @Hawkadium 4 года назад +1

    Thank you so much. Exactly what I was looking for.

  • @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

  • @luciechuard6590
    @luciechuard6590 5 лет назад +1

    Thank you, you made it very clear. I finally understand the sololean lesson x)

  • @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!

  • @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!

  • @bx6p166
    @bx6p166 4 года назад

    very helpful understanding much better

  • @the13thhour64
    @the13thhour64 14 дней назад

    great explanations to be new at this. Other videos over complicate it

  • @keithscott9774
    @keithscott9774 5 лет назад +1

    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.

  • @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?

  • @Mesdiyt
    @Mesdiyt 4 года назад

    Appreciate your effort,you made it preety clear.

  • @DeanPickersgill
    @DeanPickersgill 6 лет назад

    Great video, clear and understandable presentation - helped me immensely, thanks!

  • @shanuchandra7156
    @shanuchandra7156 6 лет назад +2

    Simply great Thank you man

  • @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.

  • @manshellramos1292
    @manshellramos1292 5 лет назад

    Thanks,​ Tom, you're the best.

  • @Paul-zr4iw
    @Paul-zr4iw 5 лет назад

    Good job

  • @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!

  • @kailashviswanathan250
    @kailashviswanathan250 4 года назад +1

    Upvoted!

  • @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.

  • @uriel-i1w
    @uriel-i1w 4 года назад

    Thanks

  • @jonathaningersoll6213
    @jonathaningersoll6213 4 года назад

    Fantastic! Thank you so much!

  • @user-qk4tx9jc4m
    @user-qk4tx9jc4m 5 лет назад

    Greatly explained!!

  • @BaronVonTacocat
    @BaronVonTacocat 6 лет назад

    Awesome explanation.
    Thanks!

  • @Layarion
    @Layarion 7 лет назад +1

    8:20 why wouldn't you just use a method to control the inputs?

  • @21agdmnm
    @21agdmnm 5 лет назад +1

    thanks cupcake

  • @Caltuit
    @Caltuit 5 лет назад

    Great explanation!

  • @manuelillanes1635
    @manuelillanes1635 4 года назад

    thanks

  • @ricks341
    @ricks341 6 лет назад

    Well done. Thanks!

  • @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

  • @AnasJayyusi
    @AnasJayyusi 6 лет назад

    thank you that was great explanation ..

  • @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.

  • @kurtgalvin
    @kurtgalvin 4 года назад

    Great video man!

  • @user-mx1ds5mf3i
    @user-mx1ds5mf3i 6 лет назад +2

    Thanks a lot:)

  • @benlee5039
    @benlee5039 6 лет назад

    Is solo learn basically the same as the .NET framework on visual studio?

  • @mohdasyraf999
    @mohdasyraf999 3 года назад

    i dont understand what Get does help

  • @kerolesmonsef4179
    @kerolesmonsef4179 5 лет назад

    nice for a beginner

  • @confidential303
    @confidential303 6 лет назад

    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 лет назад +1

      @@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.

  • @Kenken-eb5qg
    @Kenken-eb5qg 5 лет назад

    Thank you Sir!

  • @birajdarvinay95
    @birajdarvinay95 4 года назад

    This was helpful. Thanks..!!

  • @thetravelingraf
    @thetravelingraf 5 лет назад

    Awesome man

  • @arturlaherand8840
    @arturlaherand8840 4 года назад

    Thank You!

  • @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

  • @salemuae127
    @salemuae127 6 лет назад

    Have you learned programming using Sololearn website ?

  • @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 5 лет назад

    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 5 лет назад +1

      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 5 лет назад

      @@alanvargas3148 Much obliged

    • @alanvargas3148
      @alanvargas3148 5 лет назад

      @@amjad.m479 what does that mean?

    • @amjad.m479
      @amjad.m479 5 лет назад

      @@alanvargas3148 it means thank you

  • @user-qf1oz9ze6z
    @user-qf1oz9ze6z 5 лет назад

    thank you it really helped me😁😁

  • @adilarhrimaz2606
    @adilarhrimaz2606 5 лет назад

    that was helpful :D, thanks dude.

  • @FLiKEDD
    @FLiKEDD 4 года назад

    you can use bool for gender

    • @FLiKEDD
      @FLiKEDD 4 года назад

      nevermind you made a check for male female ;D

  • @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.

  • @RajenParekh13
    @RajenParekh13 7 лет назад +1

    Is this object orientated programming?

  • @unberyl
    @unberyl 5 лет назад

    Awesome explanation. It _is_ just like in Java, purely as "vanilla" getter/setter ({ get; set; }) it's pretty much useless noise code.

  • @joseluizdurigon8893
    @joseluizdurigon8893 2 года назад

    based 10:00

  • @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?

  • @FacePalmProduxtnsFPP
    @FacePalmProduxtnsFPP 6 лет назад +16

    Haven't you heard???? You can be any gender you can come up with!!! Even if it doesn't exist! Hahaha

    • @FacePalmProduxtnsFPP
      @FacePalmProduxtnsFPP 6 лет назад +1

      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 лет назад +11

      private string gender = "attack helicopter";

    • @FacePalmProduxtnsFPP
      @FacePalmProduxtnsFPP 6 лет назад +1

      A L I E N S x) beautiful

  • @legittaco4440
    @legittaco4440 3 года назад

    None of this made sense until he did hands lol

  • @xydoublehelix2924
    @xydoublehelix2924 5 лет назад

    you talk like its a Gundam, he has a youtube channel. *It'sAGundam*

  • @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 7 лет назад

    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 лет назад +2

      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