What is the { get; set; } syntax in C#? - Stack Overflow

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

The get/set pattern provides a structure that allows logic to be added during the setting ('set') ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Whatisthe{get;set;}syntaxinC#? AskQuestion Asked 11years,1monthago Modified 6monthsago Viewed 1.3mtimes 661 200 IamlearningASP.NETMVCandIcanreadEnglishdocuments,butIdon'treallyunderstandwhatishappeninginthiscode: publicclassGenre { publicstringName{get;set;} } Whatdoesthismean:{get;set;}? c# Share Follow editedAug7,2021at0:21 a3y3 80122goldbadges77silverbadges2828bronzebadges askedFeb23,2011at20:49 kn3lkn3l 18.1k2828goldbadges8484silverbadges122122bronzebadges 4 8 Ingeneralremember--settersmakeyourobjectmutable,abadidea.gettersviolate"Tellanobjectwhattodo,don'taskitforinformationandmanipulateityourself".Soingeneral,don'taddsettersandgettersbydefault.Youwillneedthem,often,butyoushouldalwaysfindarealneedbeforeyouaddthem.Inparticularsettersshouldalmostneverbeusedinproductioncode(Striveforimmutabilitywhereverpossible,andwhenmutationisneededyoushouldaskittomutateforyou,notsetavalue). – BillK Apr2,2015at22:07 13 Justtoaddsomething...Ifyoudon'tput{get;set;}youarecreatingaFieldbutifyouputthe{get;set;}youarecreatingaProperty.HavingapropertycouldmakesomethingseasierespeciallywhenworkingwithReflection. – Seichi May4,2015at21:40 2 @Seichiusingaget-settercreatesaFieldtoo,butthisoneishidden,declaredasprivateandmodifiedbytheautocreatedproperties;allofthatmadebythecompiler. – JonathanRamos May7,2017at23:12 1 aren'tautopropertiesdefeatthepurposeofprivatefields? – mireazma Jan22,2018at9:28 Addacomment  |  20Answers 20 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 644 It'saso-calledautoproperty,andisessentiallyashorthandforthefollowing(similarcodewillbegeneratedbythecompiler): privatestringname; publicstringName { get { returnthis.name; } set { this.name=value; } } Share Follow answeredFeb23,2011at20:53 KlausByskovPedersenKlausByskovPedersen 110k2828goldbadges180180silverbadges220220bronzebadges 12 115 Klaus,canyouexplainwhatwillhappenwiththiscode?Itcouldbenefitfromamorethoroughexplanation. – TylerH Nov17,2014at18:53 3 So,justtobesure:itislikeifIoverloadedthe=operator,butonlyforoneparticularelement,right? – Hi-Angel Jan12,2015at9:01 9 Whydoweneedtheprivatevar.:-/shame. – OliverDixon May29,2016at11:57 3 @TylerHThereasonfortheprivatevariableisencapsulation,theget/setprovidesa"gate"togetorsetthevariable.Althoughtherearemanyreasonsnottouseget/settersbecausethe"gate"canbreaktheencapsulationoftheprivatevariable.(itshouldn'tbeaccessible) – Alexander Mar9,2017at8:47 8 Itmaybeobvious,butIwanttoclarifythattheshorthandisnotliterallyashorthandforthat.Thatis,noprivatevariablenameiscreated.Ifyoutriedtoreferencethisprivatevariablewithintheclass,itwillfail.I'mnotsurehowC#doesit,butitbehavesasifthereisaprivatevariablewithnoname,whichyoucannotaccessinyourcode. – Denziloe Feb9,2019at18:51  |  Show7morecomments 494 SoasIunderstandit{get;set;}isan"autoproperty"whichjustlike@Klausand@Brandonsaidisshorthandforwritingapropertywitha"backingfield."Sointhiscase: publicclassGenre { privatestringname;//Thisisthebackingfield publicstringName//Thisisyourproperty { get=>name; set=>name=value; } } Howeverifyou'relikeme-aboutanhourorsoago-youdon'treallyunderstandwhatpropertiesandaccessorsare,andyoudon'thavethebestunderstandingofsomebasicterminologieseither.MSDNisagreattoolforlearningstufflikethisbutit'snotalwayseasytounderstandforbeginners.SoI'mgonnatrytoexplainthismorein-depthhere. getandsetareaccessors,meaningthey'reabletoaccessdataandinfoinprivatefields(usuallyfromabackingfield)andusuallydosofrompublicproperties(asyoucanseeintheaboveexample). There'snodenyingthattheabovestatementisprettyconfusing,solet'sgointosomeexamples.Let'ssaythiscodeisreferringtogenresofmusic.SowithintheclassGenre,we'regoingtowantdifferentgenresofmusic.Let'ssaywewanttohave3genres:HipHop,Rock,andCountry.TodothiswewouldusethenameoftheClasstocreatenewinstancesofthatclass. Genreg1=newGenre();//Herewe'recreatinganewinstanceoftheclass"Genre" //calledg1.We'llcreateasmanyasweneed(3) Genreg2=newGenre(); Genreg3=newGenre(); //Notethe()followingnewGenre.Ibelievethat'sessentialsincewe'recreatinga //newinstanceofaclass(LikeIsaid,I'mabeginnersoIcan'ttellyouexactlywhy //it'stherebutIdoknowit'sessential) Nowthatwe'vecreatedtheinstancesoftheGenreclasswecansetthegenrenamesusingthe'Name'propertythatwassetwayupabove. publicstringName//Again,thisisthe'Name'property {get;set;}//Andthisistheshorthandversiontheprocesswe'redoingrightnow Wecansetthenameof'g1'toHipHopbywritingthefollowing g1.Name="HipHop"; What'shappeninghereissortofcomplex.LikeIsaidbefore,getandsetaccessinformationfromprivatefieldsthatyouotherwisewouldn'tbeabletoaccess.getcanonlyreadinformationfromthatprivatefieldandreturnit.setcanonlywriteinformationinthatprivatefield.Butbyhavingapropertywithbothgetandsetwe'reabledobothofthosefunctions.Andbywritingg1.Name="HipHop";wearespecificallyusingthesetfunctionfromourNameproperty setusesanimplicitvariablecalledvalue.Basicallywhatthismeansisanytimeyousee"value"withinset,it'sreferringtoavariable;the"value"variable.Whenwewriteg1.Name=we'reusingthe=topassinthevaluevariablewhichinthiscaseis"HipHop".Soyoucanessentiallythinkofitlikethis: publicclassg1//We'vecreatedaninstanceoftheGenreClasscalled"g1" { privatestringname; publicstringName { get=>name; set=>name="HipHop";//insteadof'value',"HipHop"iswrittenbecause //'value'in'g1'wassetto"HipHop"bypreviously //writing'g1.Name="HipHop"' } } It'sImportanttonotethattheaboveexampleisn'tactuallywritteninthecode.It'smoreofahypotheticalcodethatrepresentswhat'sgoingoninthebackground. Sonowthatwe'vesettheNameoftheg1instanceofGenre,Ibelievewecangetthenamebywriting console.WriteLine(g1.Name);//Thisusesthe'get'functionfromour'Name'Property //andreturnsthefield'name'whichwejustsetto //"HipHop" andifweranthiswewouldget"HipHop"inourconsole. SoforthepurposeofthisexplanationI'llcompletetheexamplewithoutputsaswell usingSystem; publicclassGenre { publicstringName{get;set;} } publicclassMainClass { publicstaticvoidMain() { Genreg1=newGenre(); Genreg2=newGenre(); Genreg3=newGenre(); g1.Name="HipHop"; g2.Name="Rock"; g3.Name="Country"; Console.WriteLine("Genres:{0},{1},{2}",g1.Name,g2.Name,g3.Name); } } Output: "Genres:HipHop,Rock,Country" Share Follow editedJun30,2018at0:30 AustinWBryan 3,07433goldbadges1818silverbadges3737bronzebadges answeredApr2,2015at21:42 JosieThompsonJosieThompson 5,22811goldbadge1212silverbadges2424bronzebadges 17 21 Personallyiwouldjustcommentitoutassuchset{name=value;}//'value'hereisequalto"HipHop" – maraaaaaaaa Sep4,2015at17:18 2 @iLoveUnicorns,it'sthereforthepurposeofdataabstraction.Thebackingfieldiswhatcontainstheactualdata.Thepropertydefinitionactuallydefineshowthedataisaccessedwiththegetandsetmethods.ThelinkIprovidedhasanexcellentquotefromJohnGuttagatthetopofthepage.Iwouldrecommendreadinghisbookoreventakethisfreeonlinecourse – JosieThompson Jun3,2016at1:34 2 Can'twejustuse:publicclassGenre{publicstringName;}insteadof:publicclassGenre{publicstringName{get;set;}}.Imean,Whydoweevenneed{get;set;}? – user2048204 Nov7,2016at17:24 2 Seemslikemyconcernhasalreadybeenechoed.Ifyoudeclarethisway:"publicstringName{get;set;}"andyouaccessthisway:g1.Name="HipHop";-thenwhereistheObjectOrientation?Idon'tevenneedtheso-called"backingfield".Thebackingfielddoesn'tevenexist,asfarasIamconcerned.BecauseIonlyaccessthepublicfield.Andifthepublicfieldis"public"thenitisnotOOcompliant.Let'sallgobacktoCOBOL. – BaruchAtta Apr29,2019at12:21 3 Greatanswer,butifwearebeingpedantic,“set”isamutator,notanaccessor. – pythlang May17,2019at0:24  |  Show12morecomments 107 Thoseareautomaticproperties Basicallyanotherwayofwritingapropertywithabackingfield. publicclassGenre { privatestring_name; publicstringName { get=>_name; set=>_name=value; } } Share Follow editedJun30,2018at0:31 AustinWBryan 3,07433goldbadges1818silverbadges3737bronzebadges answeredFeb23,2011at20:51 BrandonBrandon 66.9k3030goldbadges193193silverbadges221221bronzebadges 3 10 Whatiscalled"backingfield"? – kn3l Feb23,2011at20:54 5 @stackunderflow:Thebackingfieldiswherethedataisstored.(whatisreturnedwhenusingget,andpersistedusingset).Likethecupboardtowhichgetandsetopensthedoorof. – GrantThomas Feb23,2011at20:57 6 @stackunderflow:Inthisanswer,thebackingfieldis_name.Intheautomaticproperty,thebackingfieldishidden. – Justin Feb23,2011at21:00 Addacomment  |  38 Thisistheshortwayofdoingthis: publicclassGenre { privatestring_name; publicstringName { get=>_name; set=>_name=value; } } Share Follow editedJun30,2018at0:31 AustinWBryan 3,07433goldbadges1818silverbadges3737bronzebadges answeredFeb23,2011at20:54 froeschlifroeschli 2,56422goldbadges2727silverbadges4949bronzebadges Addacomment  |  36 Itisashortcuttoexposedatamembersaspublicsothatyoudon'tneedtoexplicitlycreateaprivatedatamembers.C#willcreatesaprivatedatamemberforyou. Youcouldjustmakeyourdatamemberspublicwithoutusingthisshortcutbutthenifyoudecidedtochangetheimplementationofthedatamembertohavesomelogicthenyouwouldneedtobreaktheinterface.Soinshortitisashortcuttocreatemoreflexiblecode. Share Follow answeredFeb23,2011at20:55 KelseyKelsey 46.3k1616goldbadges122122silverbadges161161bronzebadges 2 2 Kelsey-couldyouexplainhowthissyntaxmakesitanymore"flexible"code?Idon'tseeit.Ifyouwouldaddany"logic"tothesetterorgetter,theninethercase(withorwithoutprivatedata)youwouldstillbreaktheinterface,asitis,andneedsomecoding. – BaruchAtta Apr29,2019at12:33 @BaruchAtta:changinganautopropertytoanonautopropertyorvice-versadoesnotbreaktheinterface.AninterfacesaysthatthereWILLbeagetterorsetterproperty,nothowthatisimplemented.Infact,withoutlookingatthecode,theonlywaytotellthedifferenceisbylookingatthegeneratedILandseeingthatonehasaweirdnameandonedoesn't(andinotherCLIlanguageseventhatmaynotbetrue,andit'snotpartoftheC#specsoafutureorforkedversiondoesn'thavetodothat). – jmoreno Nov25,2021at16:02 Addacomment  |  28 Basically,it'sashortcutof: classGenre{ privatestringgenre; publicstringgetGenre(){ returnthis.genre; } publicvoidsetGenre(stringtheGenre){ this.genre=theGenre; } } //InMainmethod genreg1=newGenre(); g1.setGenre("Female"); g1.getGenre();//Female Share Follow editedDec18,2018at17:11 learnAsWeGo 2,24922goldbadges1010silverbadges1818bronzebadges answeredSep12,2015at1:07 JirsonTaveraJirsonTavera 1,2131414silverbadges1515bronzebadges 3 5 Thisdoesn'tanswerthequestion.TheOPwastalkingaboutproperties. – theB Sep12,2015at1:16 8 iknowthepropertiesGetandSet,it'sanexamplethathelpunderstandbetter – JirsonTavera Sep15,2015at13:51 1 @theBinfact,OPisaskingaboutthemeaningof{get;set;},sothisanswer,Ithink,isagoodoneforthosewhocomefromotherprogramminglanguages. – carloswm85 Jul27,2021at17:55 Addacomment  |  10 Itsanauto-implementedpropertyforC#. Share Follow answeredFeb23,2011at20:50 DanielA.WhiteDanielA.White 180k4545goldbadges351351silverbadges427427bronzebadges 2 1 Eh...Doesthismeanthatyoukeepnilreferencetothestringandthenloadit'svaluefromastandardlocationwhenget;set;iscalled? – AurumAquila Feb23,2011at20:52 1 YesitkeepsnulllikeanystringvariableuntilsomeInstanceOfGenere.Name="someValue" – DanielA.White Feb23,2011at20:56 Addacomment  |  8 Theget/setpatternprovidesastructurethatallowslogictobeaddedduringthesetting('set')orretrieval('get')ofapropertyinstanceofaninstantiatedclass,whichcanbeusefulwhensomeinstantiationlogicisrequiredfortheproperty. Apropertycanhavea'get'accessoronly,whichisdoneinordertomakethatpropertyread-only Whenimplementingaget/setpattern,anintermediatevariableisusedasacontainerintowhichavaluecanbeplacedandavalueextracted.Theintermediatevariableisusuallyprefixedwithanunderscore. thisintermediatevariableisprivateinordertoensurethatitcanonlybeaccessedviaitsget/setcalls.SeetheanswerfromBrandon,ashisanswerdemonstratesthemostcommonlyusedsyntaxconventionsforimplementingget/set. Share Follow answeredJun15,2017at1:22 ChrisHalcrowChrisHalcrow 24.9k1313goldbadges140140silverbadges168168bronzebadges Addacomment  |  6 TheyaretheaccessorsforthepublicpropertyName. Youwouldusethemtoget/setthevalueofthatpropertyinaninstanceofGenre. Share Follow answeredFeb23,2011at20:51 TimCodes.NETTimCodes.NET 4,40611goldbadge2424silverbadges3535bronzebadges Addacomment  |  6 ThatisanAuto-ImplementedProperty.It'sbasicallyashorthandwayofcreatingpropertiesforaclassinC#,withouthavingtodefineprivatevariablesforthem.Theyarenormallyusedwhennoextralogicisrequiredwhengettingorsettingthevalueofavariable. YoucanreadmoreonMSDN'sAuto-ImplementedPropertiesProgrammingGuide. Share Follow answeredFeb23,2011at20:52 DusdaDusda 3,31855goldbadges3636silverbadges5858bronzebadges Addacomment  |  5 ThismeanthatifyoucreateavariableoftypeGenre,youwillbeabletoaccessthevariableasaproperty GenreoG=newGenre(); oG.Name="Test"; Share Follow editedFeb23,2011at21:02 abatishchev 94.7k7878goldbadges293293silverbadges426426bronzebadges answeredFeb23,2011at20:51 DavidBrunelleDavidBrunelle 6,3181111goldbadges5858silverbadges102102bronzebadges 1 5 Whenyoudon'tuseauto-implementedproperties,youstillabletoaccessitinthismanner.i.e.AIPisnotaboutaccessfromoutside,butaboutdeclarationinsideaclass. – abatishchev Feb23,2011at21:02 Addacomment  |  5 IntheVisualStudio,ifyoudefineapropertyXinaclassandyouwanttousethisclassonlyasatype,afterbuildingyourprojectyouwillgetawarningthatsays"FieldXisneverassignedto,andwillalwayshasitsdefaultvalue". Byaddinga{get;set;}toXproperty,youwillnotgetthiswarning. InadditioninVisualStudio2013andupperversions,byadding{get;set;}youareabletoseeallreferencestothatproperty. Share Follow editedAug29,2016at11:22 answeredAug29,2016at11:09 OmidEbrahimiOmidEbrahimi 1,11022goldbadges2020silverbadges3636bronzebadges Addacomment  |  5 Itsbasicallyashorthand.YoucanwritepublicstringName{get;set;}likeinmanyexamples,butyoucanalsowriteit: privatestring_name; publicstringName { get{return_name;} set{_name=value;}//valueisaspecialkeywordhere } Whyitisused?Itcanbeusedtofilteraccesstoaproperty,forexampleyoudon'twantnamestoincludenumbers. Letmegiveyouanexample: privateclassPerson{ privateint_age;//Person._age=25;willthrowanerror publicintAge{ get{return_age;}//example:Console.WriteLine(Person.Age); set{ if(value>=0){ _age=value;}//validexample:Person.Age=25; } } } OfficiallyitscalledAuto-ImplementedPropertiesanditsgoodhabittoreadthe(programmingguide). IwouldalsorecommendtutorialvideoC#Properties:Whyuse"get"and"set". Share Follow editedJul11,2019at18:18 toobladink 5455bronzebadges answeredDec12,2018at14:30 RandelRandel 40166silverbadges1010bronzebadges 0 Addacomment  |  5 Basicallyithelpstoprotectyourdata.Considerthisexamplewithoutsettersandgetterandthesameonewiththem. Withoutsettersandgetters ClassStudent usingSystem; usingSystem.Collections.Generic; usingSystem.Text; namespaceMyFirstProject { classStudent { publicstringname; publicstringgender; publicStudent(stringcName,stringcGender) { name=cName; gender=cGender; } } } InMain Students=newStudent("Somename","Superman");//Genderissuperman,Itworksbutitismeaningless Console.WriteLine(s.Gender); Withsettersandgetters usingSystem; usingSystem.Collections.Generic; usingSystem.Text; namespaceMyFirstProject { classStudent { publicstringname; privatestringgender; publicStudent(stringcName,stringcGender) { name=cName; Gender=cGender; } publicstringGender { get{returngender;} set { if(value=="Male"||value=="Female"||value=="Other") { gender=value; } else { thrownewArgumentException("Invalidvaluesupplied"); } } } } } InMain: Students=newStudent("somename","Other");//HereyoucansetonlythosethreevaluesotherwiseitthrowsArgumentException. Console.WriteLine(s.Gender); Share Follow answeredJun13,2021at7:52 KrishnadasPCKrishnadasPC 4,76011goldbadge4343silverbadges3939bronzebadges 3 2 I'mnewatC#,butIthinkthatthisoneisagoodexplanation. – carloswm85 Jul28,2021at13:16 whatis"value"inyourexample?Thanks – DoryNguyen Jan7at10:41 @DoryNguyen:Itseems"value"istheimplicitargumentofthesetfunction.SoifIcallmyObject.Property=875,thesetfunctionwillhave875assignedtothevariable"value".Youjusthavetoknowthat'sthesyntax.Similarly,"get"expectsyoutoreturnavalueoftheappropriatetype. – MichaelS Jan28at5:41 Addacomment  |  4 Such{get;set;}syntaxiscalledautomaticproperties,C#3.0syntax YoumustuseVisualC#2008/cscv3.5orabovetocompile. Butyoucancompileoutputthattargetsaslowas.NETFramework2.0(noruntimeorclassesrequiredtosupportthisfeature). Share Follow answeredFeb28,2013at5:39 linquizelinquize 19k99goldbadges5656silverbadges8080bronzebadges Addacomment  |  2 Getsetareaccessmodifierstoproperty. Getreadsthepropertyfield. Setsetsthepropertyvalue. GetislikeRead-onlyaccess. SetislikeWrite-onlyaccess. Tousethepropertyasreadwritebothgetandsetmustbeused. Share Follow answeredNov25,2014at21:34 communitywiki AshrafSada 1 1 ithinkgetsetarenotaccessmodifiers,infacttheyareaccessors.Accessmodifiersarelike:public,private,internaletc. – RohitArora Nov17,2015at9:45 Addacomment  |  2 Getisinvokedwhenthepropertyappearsontheright-handside(RHS) Setisinvokedwhenthepropertyappearsontheleft-handside(LHS) of'='symbol Foranauto-implementedproperty,thebackingfieldworksbehindthesceneandnotvisible. Example: publicstringLog{get;set;} Whereasforanonauto-implementedpropertythebackingfieldisupfront,visibleasaprivatescopedvariable. Example: privatestringlog; publicstringLog { get=>log; set=>log=value; } Also,itisworthnotedhereisthe'getter'and'setter'canusethedifferent'backingfield' Share Follow editedJun30,2018at0:32 AustinWBryan 3,07433goldbadges1818silverbadges3737bronzebadges answeredMay24,2017at21:47 BalaBala 4566bronzebadges 3 Thisdoesnotseemtoanswerthequestionasked. – TylerH May24,2017at22:37 Providedhintonwhentheget&setisinvoked.Alltheanswersmentionedabove,makesanimpressionthatthebackingfieldforget&setisthesame.Butitisnotthecase.Somyanswerisverymuchrelevanttothemainquestion.Hopeyouagreewithme. – Bala May30,2017at16:58 1 Foranauto-generatedproperty,whichiswhatthequestionasksabout,therecan'tbedifferentbackingfieldsusedforthegetterandthesetter;thereisonlyonebackingfield.Foranon-autoproperty(whichthequestiondoesn'taskabout)theremaynotevenconceptuallybeabackingfieldatall.Additionally,youcanwriteaprogramwithagetteronthelefthandsideofanassignmentoperatorandonewithasetterontherighthandsideofanassignmentoperator.Sonotonlyisallofthisinformationnotansweringthequestionasked,butit'sallalsowrong. – Servy May30,2017at17:00 Addacomment  |  1 Apropertyisalikealayerthatseparatestheprivatevariablefromothermembersofaclass.Fromoutsideworlditfeelslikeapropertyisjustafield,apropertycanbeaccessedusing.Property publicclassPerson { publicstringFirstName{get;set;} publicstringLastName{get;set;} publicstringFullName=>$"{FirstName}{LastName}"; } publicclassPerson { publicstringFirstName{get;set;} publicstringLastName{get;set;} publicstringFullName{get{return$"{FirstName}{LastName}";}} } FullNameisaProperty.Theonewitharrowisashortcut.Fromoutsideworld,wecanaccessFullNamelikethis: varperson=newPerson(); Console.WriteLine(person.FullName); CallersdonotcareabouthowyouimplementedtheFullName.ButinsidetheclassyoucanchangeFullNamewhateveryouwant. CheckoutMicrosoftDocumentationformoredetailedexplanation: https://docs.microsoft.com/en-us/dotnet/csharp/properties Share Follow answeredMay20,2020at6:19 MINGWUMINGWU 2,57211goldbadge1010silverbadges1515bronzebadges Addacomment  |  0 DefinethePrivatevariables InsidetheConstructorandloadthedata IhavecreatedConstantandloadthedatafromconstanttoSelectedListclass. publicclassGridModel { privateIEnumerableselectList; privateIEnumerableRoles; publicGridModel() { selectList=fromPageSizeseinEnum.GetValues(typeof(PageSizes)) select(newSelectList() { Id=(int)e, Name=e.ToString() }); Roles=fromUserroleseinEnum.GetValues(typeof(Userroles)) select(newSelectList() { Id=(int)e, Name=e.ToString() }); } publicIEnumerablePagesizelist{get{returnthis.selectList;}set{this.selectList=value;}} publicIEnumerableRoleList{get{returnthis.Roles;}set{this.Roles=value;}} publicIEnumerableStatusList{get;set;} } Share Follow editedNov26,2019at14:28 TylerH 20.4k5757goldbadges6969silverbadges9191bronzebadges answeredNov26,2019at6:57 HariLakkakulaHariLakkakula 15344bronzebadges Addacomment  |  0 Propertiesarefunctionsthatareusedtoencapsulatedata,andallowadditionalcodetobeexecutedeverytimeavalueisretrievedormodified. C#unlikeC++,VB.NetorObjective-Cdoesn’thaveasinglekeywordfordeclaringproperties,insteaditusestwokeywords(get/set)togiveamuchabbreviatedsyntaxfordeclaringthefunctions. Butitisquitecommontohaveproperties,notbecauseyouwanttorunadditionalcodewhendataisretrievedormodified,butbecauseeitheryouMIGHTwanttodosointhefutureorthereisacontractsayingthisvaluehastobeaexposedasaproperty(C#doesnotallowexposingdataasfieldsviainterfaces).Whichmeansthateventheabbreviatedsyntaxforthefunctionsismoreverbosethanneeded.Realizingthis,thelanguagedesignersdecidedtoshortenthesyntaxevenfurtherforthistypicalusecase,andadded“auto”propertiesthatdon’trequireanythingmorethanthebareminimum,towit,theenclosingbraces,andeitherofthetwokeywords(separatedbyasemicolonwhenusingboth). InVB.Net,thesyntaxforthese“auto”propertiesisthesamelengthasinc#—-PropertyXasStringvsstringX{get;set;},20charactersinbothcases.Itachievessuchsuccinctnessbecauseitactuallyrequires3keywordunderthenormalcase,andinthecaseofautopropertiescandowithout2ofthem. Removinganymorefromeither,andeitheranewkeywordwouldhavehadtobeadded,orsignificanceattachedtosymbolsorwhitespace. Share Follow answeredSep4,2021at16:15 jmorenojmoreno 13k33goldbadges5656silverbadges8484bronzebadges Addacomment  |  Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity. Nottheansweryou'relookingfor?Browseotherquestionstaggedc#oraskyourownquestion. TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia Shouldweburninatethe[term]tag? NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Visitchat Linked 53 Whatdoesthismean?publicName{get;set;} 0 Whatdoes{get;set;}means? 0 declarefunctionwithoutparenthesesinc# 0 Singletonclasscrashwhensetanattributwithnoexception -5 Cananyoneexplainthebelowcode? -1 Whatisthedifferencebetweenpropertiesandfields? 0 GetSetvsGetSetwithvariable,difference? 0 Cannotsetvariableofclass(C#) 173 Namingconvention-underscoreinC++andC#variables 14 Propertiesbackingfield-Whatisitgoodfor? Seemorelinkedquestions Related 7159 WhatisthedifferencebetweenStringandstringinC#? 2771 WhatarethecorrectversionnumbersforC#? 934 BestwaytorepeatacharacterinC# 3229 Caseinsensitive'Contains(string)' 905 Readingsettingsfromapp.configorweb.configin.NET 1084 Getpropertyvaluefromstringusingreflection 1873 WhatisaNullReferenceException,andhowdoIfixit? 1597 WhynotinheritfromList? HotNetworkQuestions WhydoAirForceplanesregularlyflyincircles? TikZarcwithextremeangle HowDoesOrbitalWarfareWork? WhywasTurningRedsetinCanadain2002andnotinpresentdayAmerica? RecreateMinecraft'slighting Howdoestheprincipleofrelativityimplythatphotonclocksandmechanicalclocksexperiencetimedilationthesameway? HowDoesBlackWinThisposition DoesDeltarequirecovidtestbeforedomesticflight? Spaceshipshooter CalculatingoverlappercentofmultiplefeaturesinsamelayerusingQGIS WhatwastheethniccompositionofSovietgovernment? Howcanfourbethehalfoffive? FrameStringsthatcontainnewlines NFA:Howdoesitfunctionwithempty-stringmoves? TheITstaffsaysthatlinuxcannotconnecttotheschool'sinternetandrefusetotry ArrangeaHaft-Sintable IsitoktohaveaPCBtrackcrossanotheronadifferentlayer? Simplequadraticfunction,butcan'tunderstandthequestion Wouldwearingfullplatearmorcauseslashingdamagetobeconvertedintobludgeoningdamage? Whatsetisthis?MinecraftandStarWars? IsitappropriatetocoldcallaprospectivepostdocPI? Doesitmakesensetoprovidea'CRediTstatement'whenIamthesoleauthor? My(manual)transmissionwon'tengageanygear1dayafterescapingbog WhatdoestheLorentzfactorrepresent? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?