CSharp examples for Custom Type:class
Create class with private field and property
using System;//from w w w .j a va 2s . c om public class Account { private decimal balance; // instance variable that stores the balance public Account(decimal initialBalance) { Balance = initialBalance; // set balance using property } // credits (adds) an amount to the account public void Credit(decimal amount) { Balance = Balance + amount; // add amount to balance } // debit (subtracts) an amount from the account public void Debit(decimal amount) { if (amount > Balance) { Console.WriteLine("Debit amount exceeded account balance."); } if (amount <= Balance) { Balance = Balance - amount; // subtract amount from balance } } 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(50.00M); // create Account object // display initial balance of account object Console.WriteLine($"account1 balance: {account1.Balance:C}"); Console.Write("Enter withdrawal amount for account1: "); // obtain user input decimal withdrawalAmount = decimal.Parse(Console.ReadLine()); Console.WriteLine($"\nsubtracting {withdrawalAmount:C} from account1 balance"); account1.Debit(withdrawalAmount); // subtract amount from account1 // display balance Console.WriteLine("account1 balance: {account1.Balance:C}"); Console.WriteLine(); Console.Write("Enter credit amount for account1: "); // obtain user input decimal creditAmount = decimal.Parse(Console.ReadLine()); Console.WriteLine("\nadding {creditAmount:C} to account1 balance"); account1.Credit(creditAmount); // display balance Console.WriteLine("account1 balance: {account1.Balance:C}"); Console.WriteLine(); } }