C# | Properties - GeeksforGeeks

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

Properties are the special type of class members that provides a flexible mechanism to read, write, or compute the value of a private field. Skiptocontent TutorialsPracticeDS&Algo.MustDoQuestionsDSATopic-wiseDSACompany-wiseAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsGeekontheTopCareersInternshipJobsApplyforJobsPostaJobJOB-A-THONEventsCourses ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningWebDevelopmentSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesIntroductionC#ProgrammingLanguageIntroductionto.NETFrameworkC#|.NETFramework(BasicArchitectureandComponentStack)HelloWorldinC#CommonLanguageRuntime(CLR)inC#FundamentalsC#|IdentifiersC#|DataTypesC#|VariablesC#|LiteralsC#|OperatorsC#|KeywordsControlStatementsC#DecisionMaking(if,if-else,if-else-ifladder,nestedif,switch,nestedswitch)SwitchStatementinC#LoopsinC#C#|JumpStatements(Break,Continue,Goto,ReturnandThrow)OOPConceptsC#|ClassandObjectC#|ConstructorsC#|InheritanceC#|EncapsulationC#|AbstractionMethodsC#|MethodsC#|MethodOverloadingC#|MethodParametersC#|MethodOverridingAnonymousMethodinC#ArraysC#|ArraysC#|JaggedArraysC#|ArrayClassHowtosortanArrayinC#|Array.Sort()MethodSet–1HowtofindtherankofanarrayinC#ArrayListArrayListinC#C#|ArrayListClassC#|ArrayvsArrayListStringC#|StringC#|VerbatimStringLiteral–@C#|StringclassStringBuilderinC#C#|StringvsStringBuilderTupleC#|TupleC#|TupleClassValueTupleinC#ValueTupleStructinC#IndexersC#|IndexersC#|MultidimensionalIndexersC#|OverloadingofIndexersPropertiesC#|PropertiesC#|RestrictionsonPropertiesCollections&GenericsCollectionsinC#C#|CollectionClassC#|Generics–IntroductionListImplementationinC#C#SortedListwithExamplesHashSetinC#withExamplesSortedSetinC#withExamplesC#DictionarywithexamplesSortedDictionaryImplementationinC#C#HashtablewithExamplesC#StackwithExamplesC#QueuewithExamplesLinkedListImplementationinC#TableofContentsIntroductionC#ProgrammingLanguageIntroductionto.NETFrameworkC#|.NETFramework(BasicArchitectureandComponentStack)HelloWorldinC#CommonLanguageRuntime(CLR)inC#FundamentalsC#|IdentifiersC#|DataTypesC#|VariablesC#|LiteralsC#|OperatorsC#|KeywordsControlStatementsC#DecisionMaking(if,if-else,if-else-ifladder,nestedif,switch,nestedswitch)SwitchStatementinC#LoopsinC#C#|JumpStatements(Break,Continue,Goto,ReturnandThrow)OOPConceptsC#|ClassandObjectC#|ConstructorsC#|InheritanceC#|EncapsulationC#|AbstractionMethodsC#|MethodsC#|MethodOverloadingC#|MethodParametersC#|MethodOverridingAnonymousMethodinC#ArraysC#|ArraysC#|JaggedArraysC#|ArrayClassHowtosortanArrayinC#|Array.Sort()MethodSet–1HowtofindtherankofanarrayinC#ArrayListArrayListinC#C#|ArrayListClassC#|ArrayvsArrayListStringC#|StringC#|VerbatimStringLiteral–@C#|StringclassStringBuilderinC#C#|StringvsStringBuilderTupleC#|TupleC#|TupleClassValueTupleinC#ValueTupleStructinC#IndexersC#|IndexersC#|MultidimensionalIndexersC#|OverloadingofIndexersPropertiesC#|PropertiesC#|RestrictionsonPropertiesCollections&GenericsCollectionsinC#C#|CollectionClassC#|Generics–IntroductionListImplementationinC#C#SortedListwithExamplesHashSetinC#withExamplesSortedSetinC#withExamplesC#DictionarywithexamplesSortedDictionaryImplementationinC#C#HashtablewithExamplesC#StackwithExamplesC#QueuewithExamplesLinkedListImplementationinC#ImproveArticle SaveArticle LikeArticle C#|PropertiesDifficultyLevel: EasyLastUpdated: 14Sep,2021BeforegoingonpropertiesletshavealookatwhytheconceptofpropertiescameintoC#?Theisbecauseoftworeasons: IfthemembersofaclassareprivatethenhowanotherclassinC#willbeabletoread,write,orcomputethevalueofthatfield.Ifthemembersoftheclassarepublicthenanotherclassmaymisusethatmember.Example: C#//C#programtoillustratetheproblems//withpublicandprivatemembersusingSystem; //publicclasspublicclassC1{         //publicdatamembers    publicintrn;    publicstringname;         //privatefield    //privateintmarks=35; } //anotherpublicclasspublicclassC2{     //MainMethodpublicstaticvoidMain(string[]args){         //CreatingobjectofC1class    C1obj=newC1();         //settingvaluestopublic    //datamembersofclassC1    obj.rn=10000;    obj.name=null;         //settingvaluestoprivate    //datamembersofclassC1    //obj.mark=0;         //displayresult    Console.WriteLine("Name: {0}\nRollNo:{1}",obj.name,obj.rn);     }}Output:  Name: RollNo:10000Explanation:InaboveyoucanseethatpublicmembersofclassC1canbeaccessedbyclassC2andusingtheobject“obj”ofC1itcanprovidethevaluestothememberslikeNameisgivenvaluenullbutwedon’twantthistobenull.C2cannotprovidethevaluetothemember“marks”becauseitisprivateinC1.Totesttheprivatememberaccessremovethecommentsandtrytorunandyoucanseethecompilerwillgiveanerror.TheProgramminglanguageswhichdonothaveproperties,usegetterandsettermethodstoprovidesuchaccessmechanism. UsingPropertiesPropertiesarethespecialtypeofclassmembersthatprovidesaflexiblemechanismtoread,write,orcomputethevalueofaprivatefield.Propertiescanbeusedasiftheyarepublicdatamembers,buttheyareactuallyspecialmethodscalledaccessors.Thisenablesdatatobeaccessedeasilyandhelpstopromotetheflexibilityandsafetyofmethods.Encapsulationandhidingofinformationcanalsobeachievedusingproperties.Itusespre-definedmethodswhichare“get”and“set”methodswhichhelptoaccessandmodifytheproperties.Accessors:Theblockof“set”and“get”isknownas“Accessors”.Itisveryessentialtorestricttheaccessibilityofproperty.Therearetwotypeofaccessorsi.e.getaccessorsandsetaccessors.Therearedifferenttypesofpropertiesbasedonthe“get”and“set”accessors: ReadandWriteProperties:Whenpropertycontainsbothgetandsetmethods.Read-OnlyProperties:Whenpropertycontainsonlygetmethod.WriteOnlyProperties:Whenpropertycontainsonlysetmethod.AutoImplementedProperties:WhenthereisnoadditionallogicinthepropertyaccessorsanditintroduceinC#3.0.ThesyntaxforDefiningProperties:  { get{//body} set{//body} }Where,canbepublic,private,protectedorinternal.canbeanyvalidC#type.canbeuser-defined.Propertiescanbedifferentaccessmodifierslikepublic,private,protected,internal.Accessmodifiersdefinehowusersoftheclasscanaccesstheproperty.Thegetandsetaccessorsforthesamepropertymayhavedifferentaccessmodifiers.Apropertymaybedeclaredasastaticpropertybyusingthestatickeywordormaybemarkedasavirtualpropertybyusingthevirtualkeyword.  GetAccessor:Itspecifiesthatthevalueofafieldcanaccesspublicly.Itreturnsasinglevalueanditspecifiestheread-onlyproperty.Example: classGeeks{ //Declareroll_nofield privateintroll_no; //Declareroll_noproperty publicintRoll_no { get { returnroll_no; } } }SetAccessor:Itwillspecifytheassignmentofavaluetoaprivatefieldinaproperty.Itreturnsasinglevalueanditspecifiesthewrite-onlyproperty. Example: classGeeks{ //Declareroll_nofield privateintroll_no; //Declareroll_noproperty publicintRoll_no { get { returnroll_no; } set { roll_no=value; } } }AccessorAccessibility  wecan’tuseaccessormodifiersonaninterfaceoranexplicitinterfacememberimplementation.wecanuseaccessormodifiersonlyifthepropertyhasbothsetandgetaccessors.Ifthepropertyisanoverridemodifier,theaccessormodifiermustmatchtheaccessoroftheoverriddenaccessor.Theaccessibilitylevelontheaccessormustbemorerestrictivethantheaccessibilitylevelontheproperty.Belowaretheprogramstodemonstratedifferenttypesofproperties:Program1:TodemonstratetheRead-Onlypropertyusing“get”accessor. C#//C#programtoillustratethe//read-onlypropertyusingSystem; publicclassStudent{     //Declarecounterfieldascnt    privatestaticintcnt;      //todefineconstructor    publicStudent()    {         //incrementthecounter        //usingconstructor        cnt++;    }      //Declarecounterproperty    publicstaticintCounter    {         //read-onlyproperty        get        {            returncnt;        }    }} classStudentTest{     //MainMethod    publicstaticvoidMain(string[]args)    {         //createthreeinstancesof        //Studentclassitcallconstructor        //threetimeswhichincreasethecounter        Students1=newStudent();        Students2=newStudent();        Students3=newStudent();          //s1.Counter=10;        //CompileTimeError:Can'tsetvalueof        //Counterbecauseitisreadonly.          Console.WriteLine("TotalNoofStudent:"+Student.Counter);          //ProgramGiveWarning        //Thevariable`s1'isassignedbutitsvalueisneverused    }}Output:  TotalNoofStudent:3Program2:Todemonstratethebothread&writepropertyusing“get”and“set”accessors. C#//C#programtoillustratethe//readandwritepropertyusingSystem; publicclassStudent{     //Declarenamefield    privatestringname="GeeksforGeeks";      //Declarenameproperty    publicstringName    {        get        {            returnname;        }         set        {            name=value;        }    }} classTestStudent{     //MainMethod    publicstaticvoidMain(string[]args)    {        Students=newStudent();          //callssetaccessorofthepropertyName,        //andpass"GFG"asvalueofthe        //standardfield'value'.        s.Name="GFG";          //displaysGFG,Callsthegetaccessor        //ofthepropertyName.        Console.WriteLine("Name:"+s.Name);    }}Output:  Name:GFG MyPersonalNotes arrow_drop_upSave LikePreviousC#|OverloadingofIndexersNext C#|RestrictionsonPropertiesRecommendedArticlesPage:25,Jun1807,Mar1908,Jul2021,Mar2221,Mar2209,Mar2228,Feb2215,Feb2215,Feb2214,Feb2214,Feb2227,Jan22ArticleContributedBy:MithunKumar@MithunKumarVotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:skajlepabhishek0719kadiyanArticleTags:CSharp-Indexers&PropertiesCSharp-OOPC#ReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinC#Top50C#InterviewQuestions&AnswersDifferencebetweenAbstractClassandInterfaceinC#C#|IsNullOrEmpty()MethodC#|HowtocheckwhetheraListcontainsaspecifiedelementString.Split()MethodinC#withExamplesMorerelatedarticlesinC#C#|ArraysofStringsC#|AbstractClassesExtensionMethodinC#C#|String.IndexOf()Method|Set-1DifferencebetweenRefandOutkeywordsinC#× Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?