Portfolio

Monday, October 12, 2015

Using Classes in C#

Example of Classes in C#       












Here I have an example of classes.  You might wonder what is classes?  What are the importance of using a class?  How classes are used?

What is a class?

According to Andrew Troelson, author of Pro C# 5.0 and .NET 4.5 Framework, a class may be composed of any number of members, which includes constructors, properties, methods, events, and data point fields.  It's the main point in Object Oriented Programming.  It's how programs are made, so it's very essential in C#.

Lets take a closer look of an example of the Employee Class.

In this example, I have made an Employee Class program that has common information about each employee, for instance the age, name, salary, starting date and phone number.  To make the program simple I have only created two employees and displayed their information by writing a console.writeline which shows each person's information.



Employee Class


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

namespace Classes
{
    class Employee
    {
        public int Age { get; set; }
        public string Name { get; set; }
        public double Salary { get; set; }
        public DateTime StartingDate { get; set; }
        public string PhoneNumber { get; set; }

        public void Bonus(double bonusPercent)
        {
            Salary += Salary * bonusPercent;
        }
        public Employee(int age, string name, double salary, string phoneNumber, DateTime startingDate)
        {
            Age= age;
            Name= name;
            Salary= salary;
            StartingDate= startingDate;
            PhoneNumber = phoneNumber;
        }
        public Employee()
        {

        }

        class Program
        {
            static void Main(string[] args)
            {
                Employee Dave = new Employee()
                {
                    Age = 35,
                    Name = "David Smith",
                    Salary = 50000.00,
                    StartingDate = new DateTime(2012, 7, 10),
                    PhoneNumber = "617-555-1212"

                };
                Console.WriteLine("Dave's age is: {0} he started on {1} and makes {2}",
                    Dave.Age, Dave.StartingDate, Dave.Salary);
                Dave.Bonus(0.05);
                Console.WriteLine("Dave's age is: {0} he started on {1} and makes {2}",
                    Dave.Age, Dave.StartingDate, Dave.Salary);



                Employee Mary = new Employee(25, "Mary Jones", 60000, "503-223-1212", new DateTime(2012, 2, 29));
                Console.WriteLine("\nMary's age is: {0} she started on {1} and makes {2}, ",
                    Mary.Age, Mary.StartingDate, Mary.Salary);
               


                Console.ReadLine();

            }
        }
    }
}

No comments:

Post a Comment