Wednesday, October 23, 2013

First take at a class evening

Here is the Program class

  using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassesExample
{
    class Program
    {
        static void Main(string[] args)
        {
            //call the mileage class and make it new
            Mileage m = new Mileage();
            //for now we are just hard coding
            //values to show the point
            //here we are assigning values to the 
            //properties
            //m is the name we gave this instance of a class
            //the dot . is a membership operator
            //it shows what belongs to the Mileage class
            m.BeginMileage = 300;
            m.EndMileage = 600;
            m.Gallons = 7;
            //in the console writeline we are calling the public
            //method CalculateGasMileage()
            Console.WriteLine(m.CalculateGasMileage().ToString("#.##"));
            Console.ReadKey();
            
        }
    }
}


Here is the Mileage class --so far

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassesExample
{
    class Mileage
    {
        //class variables or fields
        //fields should be private
        private int beginMileage;
        private int endMileage;
        private double pricePerGallon;

        //public properties are ways 
        //to expose the fields in a 
        //controlled way
        //you can do some validation
        //and testing in a property
        public double PricePerGallon
        {
            get { return pricePerGallon; }
            set { pricePerGallon = value; }
        }
        private double gallons;

      
        public double Gallons
        {
            get { return gallons; }
            set { gallons = value; }
        }
      

      
        public int BeginMileage
        {
            get { return beginMileage; }
            set { beginMileage = value; }
        }

        public int EndMileage
        {
            get { return endMileage; }
            set { endMileage = value; }
        }

        //a class can contain both private (internal)
        //methods and public methods
        private int TotalMiles()
        {
            return EndMileage - BeginMileage;
        }

        //public method accessible from other
        //classes
        public double CalculateGasMileage()
        {
            int total = TotalMiles();
            double milesPerGallon = total / Gallons;
            return milesPerGallon;
        }
    }
}

No comments:

Post a Comment