Class with a private instance variable name and public methods to Set and Get name's value. - CSharp Custom Type

CSharp examples for Custom Type:class

Description

Class with a private instance variable name and public methods to Set and Get name's value.

Demo Code

using System;//from  w w w. j  ava2s.co m
class Account
{
   private string name; // instance variable
   // method that sets the account name in the object
   public void SetName(string accountName)
   {
      name = accountName; // store the account name
   }
   // method that retrieves the account name from the object
   public string GetName()
   {
      return name; // returns name's value to this method's caller
   }
}
class MainClass
{
   static void Main()
   {
      // create an Account object and assign it to myAccount
      Account myAccount = new Account();
      // display myAccount's initial name (there isn't one)
      Console.WriteLine($"Initial name is: {myAccount.GetName()}");
      // prompt for and read the name, then put the name in the object
      Console.Write("Enter the name: "); // prompt
      string theName = Console.ReadLine(); // read the name
      myAccount.SetName(theName); // put theName in the myAccount object
      // display the name stored in the myAccount object
      Console.WriteLine($"myAccount's name is: {myAccount.GetName()}");
   }
}

Result


Related Tutorials