C# Properties (GET, SET) - Tutlane

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

In c#, properties will enable class variables to expose in a public way using get and set accessors by hiding implementation details. · In properties, a get ... C#Tutorial  C#Home  BasicsofC#  C#Introduction  C#EnvironmentSetup  C#HelloWorldProgram  C#DataTypes  C#Variables  C#Value&ReferenceTypes  C#Keywords  C#Namespaces  C#Comments  OperatorsinC#  C#Operators  C#ArithmeticOperators  C#RelationalOperators  C#LogicalOperators  C#BitwiseOperators  C#AssignmentOperators  C#OperatorsPrecedence  DecisionMakinginC#  C#IfStatement  C#IfElseStatement  C#If-Else-IfStatement  C#NestedIfStatement  C#TernaryOperator  C#SwitchStatement  IterationLoopsinC#  C#Forloop  C#WhileLoop  C#Do-WhileLoop  C#ForeachLoop  JumpStatementsinC#  C#BreakStatement  C#ContinueStatement  C#GotoStatement  C#ReturnStatement  MethodsinC#  C#Methods  C#PassByValue  C#PassByReference  C#OutParameter  C#ParamsKeyword  ArraysinC#  C#Arrays  C#MultidimensionalArrays  C#JaggedArrays  C#PassArraystoFunctions  ObjectsandClassesinC#  C#ClassesandObjects  C#Constructors  C#CopyConstructor  C#StaticConstructor  C#PrivateConstructor  C#Destructor  C#this  C#Static  C#StaticClass  C#Constant  C#Readonly  C#Structures  C#Enum  C#Properties  C#PartialClass  C#PartialMethod  StringsinC#  C#String  C#StringSplit  C#StringReplace  C#StringConcat  C#StringContains  C#Substring  C#StringCompare  C#StringRemove  C#StringFormat  C#StringEquals  C#StringClone  C#StringCopy  C#StringTrim  C#StringJoin  C#StringIndexOf  C#StringBuilder  OOPSinC#  C#AccessModifiers  C#Encapsulation  C#Abstraction  C#Inheritance  C#MethodOverloading  C#MethodOverriding  C#Virtual  C#Override  C#Base  C#Polymorphism  C#Sealed  C#Abstract  C#Interface  C#Delegates  C#Events  CollectionsinC#  C#Collections  C#Arraylist  C#HashTable  C#Queue  C#Stack  GenericsinC#  C#Generics  C#GenericConstraints  C#GenericCollections  C#List  C#SortedList  C#Dictionary  C#HashSet  FileIOinC#  C#System.IO  C#FileStream  C#TextWriter  C#TextReader  C#StreamWriter  C#StreamReader  C#BinaryWriter  C#BinaryReader  C#FileInfo  C#DirectoryInfo  C#Serialization  C#Deserialization  ExceptionHandlinginC#  C#Exception  C#ExceptionHandling  C#try-catch  C#try-catch-finally  C#throw  C#CustomException  AdvancedTopicsinC#  C#Var  C#DynamicType  C#NullableTypes  C#AnonymousTypes  C#AnonymousMethods  C#Indexer  C#Reflection  C#IEnumerable  C#Yield  C#Regex  C#StringInterpolation  C#ExtensionMethods  C#OptionalParameters  C#NamedParameters  C#Threading  C#Multithreading  C#Sleep  C#Lock  C#Timer  C#Task  C#Tuple  C#ValueTuple  C#LINQ  C#Func  C#Action  C#Predicate C#Properties(GET,SET) Inc#,Propertyisanextensionoftheclassvariable.It providesamechanismtoread,write,orchangetheclassvariable'svalue withoutaffectingtheexternalwayofaccessingitinourapplications.   Inc#,propertiescancontainoneortwocodeblockscalledaccessors,and thosearecalledagetaccessorandsetaccessor.Byusinggetandsetaccessors,wecanchangetheinternalimplementationofclass variables andexposeitwithoutaffectingtheexternalwayofaccessingitbasedonourrequirements.   Generally,inobject-orientedprogramminglanguageslikec#youneedtodefinefieldsasprivate andthenusepropertiestoaccesstheirvaluesina publicwaywithgetandsetaccessors.   Followingisthesyntaxofdefiningapropertywithgetandsetaccessorinc#programminglanguage.   {  get  {    //returnpropertyvalue  }  set  {   //setanewvalue  }} Ifyouobservetheabovesyntax,weusedanaccessmodifierand returntypetodefineapropertyalongwithgetandsetaccessorstomakerequiredmodificationstotheclass variables basedonourrequirements.   Here,thegetaccessorcodeblockwillbeexecutedwheneverthepropertyisread,andthecodeblockofsetaccessorwillbeexecutedwheneverthepropertyisassignedtoanewvalue.   Inc#,thepropertiesarecategorizedintothreetypes,thoseare.   TypeDescription Read-Write Apropertythatcontainsabothgetandsetaccessors,thenwewillcallitaread-writeproperty. Read-Only Apropertythatcontainsonlygetaccessor,thenwewillcallitaread-onlyproperty. Write-Only Apropertythatcontainsonlysetaccessor,thenwewillcallitawrite-onlyproperty. Inc#,Propertieswon’tacceptanyparameters,andweshouldnotpassapropertyasareforoutparameterinourapplication.   Followingisthesimpleexampleofdefiningaprivatevariableandapropertyinthec#programminglanguage.   classUser{  privatestringname;  publicstringName  {    get{returnname;}    set{name=value;}  }} Ifyouobservetheaboveexample,wedefinedapropertycalled“Name”andweusedagetaccessortoreturnapropertyvalueandsetaccessorstosetanewvalue.Here,thevalue keyword in set accessorisusedtodefineavaluethatisbeingassignedby set accessor.   Inc#,the get accessorneedstobeusedonlytoreturnthefieldvalueortocomputeitandreturnit,butweshouldnotuseitforchangingthestateofanobject.   Asdiscussed,wecanextendthebehaviorofclass variables usingproperties get and set accessors.Followingistheexampleofextendingthebehaviorofprivate variable inpropertyusing get and set accessors inc#programminglanguage.   classUser{  privatestringname="SureshDasari";  publicstringName  {   get   {     returnname.ToUpper();   }   set   {     if(value=="Suresh")       name=value;   }  }} Ifyouobservetheaboveexample,weareextendingthebehaviorofprivate variable nameusingapropertycalledNamewithgetandsetaccessorsbyperformingsomevalidationsliketomakesureNamevalueequalstoonly“Suresh”usingsetaccessorandconvertingpropertytexttouppercasewithgetaccessor.   Herethefield“name”ismarkedasprivate,soifyouwanttomakeanychangestothisfield,wecandoitonlybycallingtheproperty(Name).   Inc#properties,the get accessorwillbeinvokedwhilereadingthevalueofaproperty,andwhenweassignanewvaluetotheproperty,thenthe set accessorwillbeinvokedbyusinganargumentthatprovidesthenewvalue.   Followingistheexampleofinvoking get and set accessorsofpropertiesinc#programminglanguage.   Useru=newUser();u.Name="Rohini";//setaccessorwillinvokeConsole.WriteLine(u.Name);//getaccessorwillinvoke Intheaboveexample,whenweassignanewvaluetotheproperty,thenthe set accessorwillbeinvokedandthe get accessorwillbeinvokedwhenwetrytoreadthevaluefromtheproperty. C#Properties(Get,Set)Example Followingistheexampleofdefiningproperties with get and set accessorstoimplementrequiredvalidationswithoutaffectingtheexternalwayofusingitinthec#programminglanguage.   usingSystem;namespaceTutlane{   classUser   {    privatestringlocation;    privatestringname="SureshDasari";    publicstringLocation    {      get{returnlocation;}      set{location=value;}    }    publicstringName    {      get      {        returnname.ToUpper();      }      set      {        if(value=="Suresh")         name=value;      }    }   }   classProgram   {    staticvoidMain(string[]args)    {      Useru=newUser();      //setaccessorwillinvoke      u.Name="Rohini";      //setaccessorwillinvoke      u.Location="Hyderabad";      //getaccessorwillinvoke      Console.WriteLine("Name:"+u.Name);      //getaccessorwillinvoke      Console.WriteLine("Location:"+u.Location);      Console.WriteLine("\nPressEnterKeytoExit..");      Console.ReadLine();    }   }} Ifyouobservetheaboveexample,weareextendingthebehaviorofprivate variables (name,location)usingproperties(Name,Location)with get and set accessorsbyperformingsomevalidationsliketomakesureNamevalueequalstoonly“Suresh”using set accessorandconvertingpropertytexttouppercasewith get accessor.   Whenyouexecutetheabovec#program,wewillgettheresultasshownbelow.     Ifyouobservetheaboveexample,ourvariabletextconvertedtouppercase,andevenafterwesetvariabletextas“Rohini”,itdisplayedtextas“SureshDasari”becauseofthe set accessorvalidationfailsintheproperty. C#CreateRead-OnlyProperties Asdiscussed,ifapropertycontainstheonly get accessor,thenwewillcallita read-onlyproperty. Followingistheexampleofcreating read-only properties inthec#programminglanguage.   usingSystem;namespaceTutlane{  classUser  {    privatestringname;    privatestringlocation;    publicUser(stringa,stringb)    {     name=a;     location=b;    }    publicstringName    {     get     {       returnname;     }    }    publicstringLocation    {     get     {       returnlocation;     }    }  }  classProgram  {    staticvoidMain(string[]args)    {      Useru=newUser("SureshDasari","Hyderabad");      //compileerror      //u.Name="Rohini";      //getaccessorwillinvoke      Console.WriteLine("Name:"+u.Name);      //getaccessorwillinvoke      Console.WriteLine("Location:"+u.Location);      Console.WriteLine("\nPressEnterKeytoExit..");      Console.ReadLine();    }  }} Ifyouobservetheaboveexample,wecreatedpropertiesusingonly get accessortomakethepropertiesare read-only basedonourrequirements.   Ifweuncommentthecommentedcode,wewillgetacompileerrorbecauseourNamepropertydoesn’tcontainany set accessortosetanewvalue.It’sjust read-only property.   Whenyouexecutetheabovec#program,youwillgetaresultlikeasshownbelow.     Thisishowwecancreate read-only propertiesinc#applicationsbasedonourrequirements. C#CreateWriteOnlyProperties Asdiscussed,ifapropertycontainstheonly set accessor,thenwewillcallitawrite-onlyproperty. Followingistheexampleofcreatingwrite-onlyproperties inthec#programminglanguage.   usingSystem;namespaceTutlane{   classUser   {    privatestringname;    publicstringName    {      set      {       name=value;      }    }    privatestringlocation;    publicstringLocation    {      set      {        location=value;      }    }    publicvoidGetUserDetails()    {      Console.WriteLine("Name:"+name);      Console.WriteLine("Location:"+location);    }   }   classProgram   {     staticvoidMain(string[]args)     {       Useru=newUser();       u.Name="SureshDasari";       u.Location="Hyderabad";       //compileerror       //Console.WriteLine(u.Name);       u.GetUserDetails();       Console.WriteLine("\nPressEnterKeytoExit..");       Console.ReadLine();     }   }} Ifyouobservetheaboveexample,wecreatedpropertiesusingonly set accessortomakethepropertiesarewrite-onlybasedonourrequirements.   Ifweuncommentthecommentedcode,thenwewillgetacompileerrorbecauseourNamepropertydoesn’tcontainany get accessortoreturnavalue.It’sajustwrite-onlyproperty.   Whenyouexecutetheabovec#program,youwillgetaresultlikeasshownbelow.     Thisishowwecancreatewrite-onlypropertiesinc#applicationsbasedonourrequirements. C#AutoImplementedProperties Inc#,apropertyiscalledanauto-implementedpropertywhenitcontainsaccessors(get,set)withouthavinganylogicimplementation.   Generally,theauto-implementedpropertiesareusefulwheneverthereisnologicimplementationrequiredinpropertyaccessors.   Followingistheexampleofcreatingauto-implementedpropertiesinthec#programminglanguage.   usingSystem;namespaceTutlane{   classUser   {    publicstringName{get;set;}    publicstringLocation{get;set;}   }   classProgram   {     staticvoidMain(string[]args)     {       Useru=newUser();       u.Name="SureshDasari";       u.Location="Hyderabad";       Console.WriteLine("Name:"+u.Name);       Console.WriteLine("Location:"+u.Location);       Console.WriteLine("\nPressEnterKeytoExit..");       Console.ReadLine();     }   }} Ifyouobservetheaboveexample,wecreatedpropertieswith get and set accessorswithouthavinganylogicimplementation.   Whenyouexecutetheabovec#program,wewillgetaresultlikeasshownbelow.     Thisishowwecancreateauto-implementedpropertiesinc#applicationsbasedonourrequirements. C#PropertiesOverview Thefollowingaretheimportantpointswhichweneedtorememberaboutpropertiesinthec#programminglanguage.   Inc#,propertieswillenableclassvariablestoexposeinapublicwayusing get and set accessorsbyhidingimplementationdetails. Inproperties,a get accessorisusedtoreturnapropertyvalueanda set accessorisusedtoassignanewvalue. The value  keyword in set accessorisusedtodefineavaluethatisgoingtobeassignedbythe set accessor. Inc#,thepropertiesarecategorizedasread-write,read-only,orwrite-only. Previous   Next    TableofContents PropertiesinC#withExamples C#Properties(GetSet)Example C#ReadOnlyPropertieswithExamples C#WriteOnlyPropertieswithExamples C#AutoImplementedPropertieswithExamples



請為這篇文章評分?