c# classes and objects

Think "nouns" not "verbs"...



a class is a container for code
Class is a blueprint (template) to create an object which is always a reference type. A class can contain data and methods. Concepts: Encapsulation hide detail links data and methods bound together Inheritance " is a " relationships between similar items creates class hierarchy Polymorphism many shapes / forms a method can be implemented many ways depending on type
   class Program
   {
       static void Main() 
       { 
           // Pass the array as a parameter
           int[,] list = new int[6, 6];
           PrintArray(list);
       }

       static void PrintArray(int[,] arr)  // pass in the 2d array
       {
           // Get upper bounds for the array.
           // This is the max index, NOT the count
           int bound0 = arr.GetUpperBound(0);
           int bound1 = arr.GetUpperBound(1);

           // Display the array elements: 
           // MUST use "<=" as the bound is the the index n-1 in an array of n
           for (int i = 0; i <= bound0; i++) 
           { 
               for (int j = 0; j <= bound1; j++) 
               { 
                   Console.Write(arr[i, j] + " "); // writes out each column of the row 
               }
               Console.WriteLine(); // advances to the next line for next row
           } 
       } 
   }
   

a class is a template or blueprint for objects
Class is a blueprint (template) to create an object which is always a reference type. A class can contain data and methods. Class with TWO methods ---------------------- 1. IsItEven - an instance method - needs to be instantiated to use - a member of the instantiated object 2. SumRange - a static method - does NOT need to be instantiate - is a member of the class
                    
    public class MathLib
    {
        // bool                        // to call this method in the library
        public bool IsItEven(int num)  ClassLibrary1.MathLib lib = new ClassLibrary1.MathLib();
        {                              Console.WriteLine( lib.IsItEven(numIn).ToString() );
            if (num % 2 == 0)
                return true;
            return false;
        }
              
        
        /////////////////////////////  // to call this method in the library
        // wyatt                       Console.WriteLine(ClassLibrary1.MathLib.SumRange(1, numIn));              
        //    accepts 2 ints                    
        //    loops from start to end
        //       calculates the sum
        //    return a decimal sum 
        //////////////////////////////
        public static decimal SumRange(int start, int end)
        {
            // use decimal to be able to hold LARGE sums
            decimal sum = 0;

            // loop from start to end accumulating the sum
            while (start <= end)
            {
                checked
                {
                    sum += (decimal)start++;
                }
            }

            // give back the calculated sum
            return sum;
        }  
    }

   

simple class example
   // rob miles...

   // instantiated by the Bank class below
   class Account 
   { 
       private decimal balance = 0; 
       public bool WithdrawFunds ( decimal amount ) 
       { 
           if ( balance < amount ) 
           { 
               return false ; 
           } 
           balance = balance - amount ; 
           return true; 
       } 
   }

   // Main() is always static and always called first
   // (what about a winforms program?? )
   class Bank 
   { 
       public static void Main () 
       { 
           Account RobsAccount; 
           RobsAccount = new Account(); 
           if ( RobsAccount.WithdrawFunds (5) ) 
           { 
               Console.WriteLine ( "Cash Withdrawn" ) ; 
           } 
           else 
           { 
               Console.WriteLine ( "Insufficient Funds" ) ; 
           } 
       } 
   }
   

static members of a class
   // from rob miles yellow book, chapter 4 ...

   public class Account 
   {
       // these are static meaning they are members of the "class", not the instantiated object   
       private static decimal minIncome ; 
       private static int minAge ; 
     
       // this is a static method - same idea and why we don't need to instantiate to use this method
       public static bool AccountAllowed(decimal income, int age) 
       { 
           if ( ( income > minIncome) && ( age > minAge) ) 
           { 
               return true; 
           } 
           else 
           { 
           return false; 
           } 
       } 
       
       // this would be part of the instantiated 
       // object for OBVIOUS reasons
       private decimal balance = 0; 
       public bool WithdrawFunds ( decimal amount ) 
       { 
           if ( balance < amount ) 
           { 
               return false ; 
           } 
           balance = balance - amount ; 
           return true; 
       } 
       
   }
   
If you think about it, this makes perfect sense. The limit values should not be held as members of a class, since we want them to be the same for all instances of the class, therefore, make them static.

class code examples

see "GridWithClass" Project - a class definition
   // =========================================================
   // constructor with values - NO return specified in a constructor
   public RandomGrid2d(int rows, int cols)
   {
       // error checking fragile here - will STILL CREATE OBJECT, so need to make sure
       // that you have a stable valid object , else throw an exception back to the caller
       if (rows < 0 || cols < 0 || rows > MAX_SIZE || cols > MAX_SIZE)
       {
           // set the field values to deafult, putting object into a known state            
           r = c = DEFAULT_SIZE;

           // throw exception? crash program if it doesn't handle exception (try/catch)
           // throw new System.ArgumentException("Specified grid size incorrect.");

           // put object into 'zombie' state - an internal state marked as invalid

           // report error?  how? win? or console? throw exception?
           string s = "Specified grid size not supported. Creating square \ngrid using default value of "
                       + DEFAULT_SIZE + " rows and columns";

           if (true)// how to know if windows or console program?
               System.Console.WriteLine(s);
           //else
               //System.Windows.Forms.MessageBox.Show(s);

       }
       else // okay size
       {
           r = rows;
           c = cols;
       }

       // create & populate the grid and assign the ref var
       grid = new int[r, c];
       for (int i = 0; i < r; i++)
           for (int j = 0; j < c; j++)
               grid[i, j] = rnd.Next(1, System.Math.Max(r, c) + 1);
   }


   // =========================================================
   // print the grid - overloaded
   public void PrintRandomGrid(System.Windows.Forms.TextBox txtOut)
   {
       txtOut.AppendText(System.Environment.NewLine); // skip a line
       // use field values r & c print rows & columns
       for (int i = 0; i < r; i++)
       {
           for (int j = 0; j < c; j++)
               txtOut.AppendText(grid[i, j].ToString("x1") + " ");
           txtOut.AppendText(System.Environment.NewLine);
       }
       txtOut.AppendText(System.Environment.NewLine); // skip a line
   }