replaces public methods SetName and GetName with a public Name property. - CSharp Custom Type

CSharp examples for Custom Type:class

Description

replaces public methods SetName and GetName with a public Name property.

Demo Code

using System;//w  w  w. j a  v  a 2 s .  co  m
class Account
{
   private string name; // instance variable
   // property to get and set the name instance variable
   public string Name
   {
      get // returns the corresponding instance variable's value
      {
         return name; // returns the value of name to the client code
      }
      set // assigns a new value to the corresponding instance variable
      {
         name = value; // value is implicitly declared and initialized
      }
   }
}
class AccountTest
{
   static void Main()
   {
      // create an Account object and assign it to myAccount
      Account myAccount = new Account();
      // display myAccount's initial name
      Console.WriteLine($"Initial name is: {myAccount.Name}");
      // prompt for and read the name, then put the name in the object
      Console.Write("Please enter the name: "); // prompt
      string theName = Console.ReadLine(); // read a line of text
      myAccount.Name = theName; // put theName in myAccount's Name
      // display the name stored in object myAccount
      Console.WriteLine($"myAccount's name is: {myAccount.Name}");
   }
}

Result


Related Tutorials