Getters setters and auto properties in C# explained { get; set

文章推薦指數: 80 %
投票人數:10人

I have had a few questions from people asking me to elaborate on the concept of Getters and Setters in C#, specifically around the { get; ... Skiptocontent GetterssettersandautopropertiesinC#explained{get;set;} Home/c#,GameDevelopment/GetterssettersandautopropertiesinC#explained{get;set;} Previous Next ViewLargerImage GetterssettersandautopropertiesinC#explained{get;set;} IthasbeenawhilesinceIlastposted,ithasbeenabusyyearwithanewjavascriptdevelopmentjobandmydaughterbeingborn.Thingshavestartedtosettledownalittle,soIthoughtitmightbeagoodtimetokickthingsoffbydivingintosomec#tutorials,IwillthenlikelyreturntosomeUnityspecificstuff,andmaybeevenjavascriptgamedevposts. IhavehadafewquestionsfrompeopleaskingmetoelaborateontheconceptofGettersandSettersinC#,specificallyaroundthe{get;set;}syntax(alsoknownasanautoproperty). IfyouhavehadanydealingswithC#youwilllikelyhaveseenvariablesdeclaredinthefollowingformat: publicclassMyClass { publicstringmyProperty{get;set;} } TheaboveimplementationisknowninCSharpasanAutoProperty,orAutoImplementationProperty,becausewhenthecodeiscompileditwillautomaticallyconvertthelineintoamoretraditionalgetter/setterfunctionblocksuchasthis: publicclassMyClass { privatestring_myProperty;//alsoknownasa'backingfield' publicstringMyProperty { get { returnmyProperty; } set { myProperty=value; } } } Basicallyspeaking,it’sashorthandsinglelineversionofthemoreverboseimplementationdirectlyabove. Theyaretypicallyusedwhennoextralogicisrequiredwhengettingorsettingthevalueofavariable. Thevaluescanthenbeaccessedandmutated(changed)fromanexternalclasslikeso: myClass=newMyClass() stringfoo=myClass.MyProperty;//getting myClass.MyProperty="john";//setting Youcandefineanycombinationofgetorsetdependingonhowyouwouldlikeyourpropertytobeaccessible,forInstance: publicstringmyProperty{get;} Thiswillallowanexternalclasstogetthevalueofthisproperty,butnotsetit–ausefulwaytoprotectagainstdatamutation. WhennewtoC#,itmaybetemptingtojustgiveallpropertiesbothgettersandsetters,whichunlesstheyexplicitlyneedtobemutable,isbadpractice. “Tellanobjectwhattodo,don’taskitforinformationandmanipulateityourself”.Withthatinmind,don’taddsettersandgettersbydefault.Ifavariabledoesnotneedtobeaccessedatallbyotherclasses,makeitprivateinstead. Andifthereisneedforexternalclassaccess,trytohaveagoodreasontouseasetter! Discussionsontheethicsofdatamutation/immutabilitycangetcomplexfastdependingonwhoyouarespeakingto,butifyouareabeginner,donotfrettoomuch,asthemoreelaborateconceptswillpresentthemselvesasyourjourneycontinues.Masterthebasicsfirst. Let’sSummarise Avoidmakingallpropertiespublic,becauseit'sjustafreeforallandhowspaghetticodeiscookedup. publicstringmyValue;//don'tdothis IfyouhaveapropertythatdoesNOTneedtobeaccessedbyotherclasses,makeitprivate. AndIfcomingfromUnity,andyouwanttoexposethevariableinUnity’spropertyinspector, serializeitinsteadlikeso: [SerializeField]//exposethevariableinthepropertyinspector,eventhoughit'sprivate privatestring_myValue; Ifyourequireaccesstoaclassmembervariable’svaluefromanotherclass,giveitagetterlikeso: publicstringmyValue{get;} Andifyoushouldalsoneedtochangethedatafromanotherclass,youcanaddasetteralso: publicstringmyValue{get;set;} Asmentionedearlier,bemindfulofusingsetters,asitbasicallymeansanythingcanchangeanythingelse,whichcanleadtoalltypesofproblemsonceaprojectgrows. Byjohnstejskal|2020-03-17T13:17:31+00:00September3rd,2017|Categories:c#,GameDevelopment|Tags:c#,csharp|1Comment ShareThisStory,ChooseYourPlatform! facebooktwitterlinkedinredditpinterestvk AbouttheAuthor: johnstejskal RelatedPosts IndieGameLaunchFailsBADLY.MyResponseandAnalysis November8th,2021 | 0Comments HowtostoprigidbodiesslidingandfallingoffmovingplatformsinUnity3dand2D August27th,2016 | 1Comment Mylatestprojectlaunched,TheSolarJourney–An3Dinteractivewebadventurethroughthesolarsystem June9th,2016 | 0Comments PlayingsoundandmusiconmobilewiththeWebAudioAPI October25th,2015 | 0Comments AnIntroductiontotheWebAudioAPI October24th,2015 | 0Comments OneComment AtifShafiqueSatti May18,2018at11:55am-Reply Whataboutgetset/propertyforuser-defineddatatypeslikestructureetc.Iwaslookingatthistopichttps://www.codeslehrer.com/c-sharp-get-set-functions/Thereisanexamplecanyouconfirmthatitistherightwaylike: publicStructExnStruct { get{returnnewStruct;} set{newStruct=value;} } LeaveACommentCancelreplyComment Savemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment. ProtectedbyWPAntiSpam Categories c# GameDevelopment JavaScript Uncategorized Unity3D ToggleSlidingBarArea ThisIsACustomWidget ThisSlidingBarcanbeswitchedonoroffinthemeoptions,andcantakeanywidgetyouthrowatitorevenfillitwithyourcustomHTMLCode.Itsperfectforgrabbingtheattentionofyourviewers.Choosebetween1,2,3or4columns,setthebackgroundcolor,widgetdividercolor,activatetransparency,atopborderorfullydisableitondesktopandmobile. GetSocial



請為這篇文章評分?