A public constructor initializes private instance variable balance through public property. : public « Class Interface « C# / C Sharp






A public constructor initializes private instance variable balance through public property.




using System;

public class Account
{
   private decimal balance; 

   public Account( decimal initialBalance )
   {
      Balance = initialBalance; 
   } 
   public void Credit( decimal amount )
   {
      Balance = Balance + amount; 
   } 
   public decimal Balance
   {
      get
      {
         return balance;
      } 
      set
      {
         if ( value >= 0 )
            balance = value;
      }
   } 
} 

public class AccountTest
{
   public static void Main( string[] args )
   {
      Account account1 = new Account( 5.00M ); 
      Account account2 = new Account( -7.53M ); 

      Console.WriteLine( "account1 balance: {0:C}",account1.Balance ); 
      Console.WriteLine( "account2 balance: {0:C}\n",account2.Balance );

      decimal depositAmount; 

      Console.Write( "Enter deposit amount for account1: " );
      depositAmount = Convert.ToDecimal( Console.ReadLine() );
      Console.WriteLine( "adding {0:C} to account1 balance\n",depositAmount );
      account1.Credit( depositAmount ); 

      Console.WriteLine( "account1 balance: {0:C}",account1.Balance );
      Console.WriteLine( "account2 balance: {0:C}\n",account2.Balance );

      Console.Write( "Enter deposit amount for account2: " );
      depositAmount = Convert.ToDecimal( Console.ReadLine() );
      Console.WriteLine( "adding {0:C} to account2 balance\n",depositAmount );
      account2.Credit( depositAmount ); 

      Console.WriteLine( "account1 balance: {0:C}", account1.Balance );
      Console.WriteLine( "account2 balance: {0:C}", account2.Balance );
   }
}


       








Related examples in the same category

1.Class declaration with one public method.
2.Class declaration with a public method that has a parameter.
3.MyClass class with a public constructor to initialize the course name.
4.User-defined public method