C# | Properties - GeeksforGeeks
文章推薦指數: 80 %
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:
延伸文章資訊
- 1Properties In C#
Property in C# is a member of a class that provides a flexible mechanism for classes to expose pr...
- 2自動實作的屬性- C# 程式設計手冊 - Microsoft Docs
Its data can be modified from // outside the class. class Customer { // Auto-implemented properti...
- 3屬性- C# 程式設計手冊
_seconds = value * 3600; } } } class Program { static void Main() { TimePeriod t = new TimePeriod...
- 4屬性(Property) 與欄位(Field) - mrkt 的程式學習筆記
Property:FullDescription為主要資料取得的地方,對外公開;. Field:_FullDescription為物件私有成員,是用來存放屬性的資料。 MSDN - 使用屬性(C...
- 5C# Properties (Get and Set) - W3Schools
C# also provides a way to use short-hand / automatic properties, where you do not have to define ...