Partial Classes in C# - GeeksforGeeks

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

A partial class is a special feature of C#. It provides a special ability to implement the functionality of a single class into multiple ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#HTMLJavaScriptPHPSQLScalaPerlGoLanguageKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblems ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesC#|StaticClassPartialClassesinC#PartialMethodsinC#ExtensionMethodinC#LocalFunctioninC#C#|DelegatesC#|PredicateDelegateC#|ActionDelegateC#|FuncdelegateDelegatesvsInterfacesinC#C#|ExplicitInterfaceImplementationGarbageCollectioninC#|.NETFrameworkSettinguptheenvironmentinC#HelloWorldinC#CommonLanguageRuntime(CLR)inC#C#|IdentifiersC#|DataTypesC#|VariablesC#|LiteralsC#|OperatorsC#|KeywordsSwitchStatementinC#LoopsinC#C#|JumpStatements(Break,Continue,Goto,ReturnandThrow)C#|ClassandObjectC#|IsNullOrEmpty()MethodDifferencebetweenAbstractClassandInterfaceinC#C#|ArraysofStringsC#|HowtocheckwhetheraListcontainsaspecifiedelementString.Split()MethodinC#withExamplesC#|StaticClassPartialClassesinC#PartialMethodsinC#ExtensionMethodinC#LocalFunctioninC#C#|DelegatesC#|PredicateDelegateC#|ActionDelegateC#|FuncdelegateDelegatesvsInterfacesinC#C#|ExplicitInterfaceImplementationGarbageCollectioninC#|.NETFrameworkSettinguptheenvironmentinC#HelloWorldinC#CommonLanguageRuntime(CLR)inC#C#|IdentifiersC#|DataTypesC#|VariablesC#|LiteralsC#|OperatorsC#|KeywordsSwitchStatementinC#LoopsinC#C#|JumpStatements(Break,Continue,Goto,ReturnandThrow)C#|ClassandObjectC#|IsNullOrEmpty()MethodDifferencebetweenAbstractClassandInterfaceinC#C#|ArraysofStringsC#|HowtocheckwhetheraListcontainsaspecifiedelementString.Split()MethodinC#withExamplesPartialClassesinC#ViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 17Nov,2020ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle ApartialclassisaspecialfeatureofC#.Itprovidesaspecialabilitytoimplementthefunctionalityofasingleclassintomultiplefilesandallthesefilesarecombinedintoasingleclassfilewhentheapplicationiscompiled.Apartialclassiscreatedbyusingapartialkeyword.Thiskeywordisalsousefultosplitthefunctionalityofmethods,interfaces,orstructureintomultiplefiles.Syntax:  publicpartialClas_name { //code } Importantpoints: Whenyouwanttochopthefunctionalityoftheclass,method,interface,orstructureintomultiplefiles,thenyoushouldusepartialkeywordandallthefilesaremandatorytobeavailableatcompiletimeforcreatingthefinalfile.Thepartialmodifiercanonlypresentinstantlybeforethekeywordslikestruct,class,andinterface.Everypartofthepartialclassdefinitionshouldbeinthesameassemblyandnamespace,butyoucanuseadifferentsourcefilename.Everypartofthepartialclassdefinitionshouldhavethesameaccessibilityasprivate,protected,etc.Ifanypartofthepartialclassisdeclaredasanabstract,sealed,orbase,thenthewholeclassisdeclaredofthesametype.Theuserisalsoallowedtousenestedpartialtypes.Dissimilarpartsmayhavedissimilarbasetypes,butthefinaltypemustinheritallthebasetypes.Example:Here,wearetakingaclassnamedGeeksandsplitthedefinitionofGeeksclassintotwodifferentfilesnamedGeeks1.cs,andGeeks2.csasshownbelow: InGeeks1.cs,andGeeks2.cs,apartialclassiscreatedusingthepartialkeywordandeachfilecontainsdifferentfunctionalityofGeeksclassasshownbelow.Geeks1.csC#publicpartialclassGeeks{    privatestringAuthor_name;    privateintTotal_articles;     publicGeeks(stringa,intt)    {        this.Authour_name=a;        this.Total_articles=t;    }}Geeks2.cs C#publicpartialclassGeeks{    publicvoidDisplay()    {        Console.WriteLine("Author'snameis:"+Author_name);        Console.WriteLine("Totalnumberarticlesis:"+Total_articles);    }}Whenweexecutetheabovecode,thecompilercombinesGeeks1.csandGeeks2.csintoasinglefile,i.e.Geeksasshownbelow.GeeksThisclassmaycontaintheMainMethod.Forsimplicity,hereMain()methodisnotincluded. C#publicclassGeeks{    privatestringAuthor_name;    privateintTotal_articles;     publicGeeks(stringa,intt)    {        this.Authour_name=a;        this.Total_articles=t;    }     publicvoidDisplay()    {        Console.WriteLine("Author'snameis:"+Author_name);        Console.WriteLine("Totalnumberarticlesis:"+Total_articles);    }}Advantages: Withthehelpofpartialclasses,multipledeveloperscanworksimultaneouslyinthesameclassindifferentfiles.Withthehelpofapartialclassconcept,youcansplittheUIofthedesigncodeandthebusinesslogiccodetoreadandunderstandthecode.Whenyouwereworkingwithautomaticallygeneratedcode,thecodecanbeaddedtotheclasswithouthavingtorecreatethesourcefilelikeinVisualstudio.Youcanalsomaintainyourapplicationinanefficientmannerbycompressinglargeclassesintosmallones. MyPersonalNotes arrow_drop_upSave LikePreviousC#|StaticClassNext PartialMethodsinC#RecommendedArticlesPage:13,Dec1824,Dec1826,Aug1928,Sep2120,Nov2112,Nov1805,Sep2221,Aug2221,Aug2215,Aug2201,Aug2220,Jul22ArticleContributedBy:ankita_saini@ankita_sainiVotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:adonislanArticleTags:CSharp-OOPC#ReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?