How To Create Classes, Objects and Constructors in C#

Problem: 

First, create a main program and then define a new class in its own file. Call the class Car. Give it a single method called "Start". Make the method simply print "Car started!". In your main program, create a new Car object and call its Start() method. Your final program should simply therefore display the text "Car started!".

 Solution: 

 Main Program:

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

namespace Cave7Class
{
    class Program
    {
        static void Main(string[] args)
        {
            Car obj = new Car();
            obj.Start();
        }
    }
}



Class Car


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

namespace Cave7Class
{
    class Car
    {
        public void Start()
        { 
            Console.WriteLine("Car Started" );
            Console.ReadLine();
        }

    }
}





Constructors 

Problem:

 Modify the above Car class so that it has an instance variable called name of type string Add a constructor that accepts a string parameter and sets the car's name using this parameter. Add a GetName() method that returns the car's name. Finally, modify the main application so that it sets the car's name via the constructor, then prints the cars name (retrieving it using GetName())

 Class Car


using System;




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

namespace Cave7Class
{
    class Car
    {
        string name;
        public Car ( string name)
        {
            this.name = name;
        }
        public string Getname()
        {
            return name;
        }
        public void Start()
        { 
            Console.WriteLine("Car started!" );
           
        }

    }
}


Main Program:



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

namespace Cave7Class
{
    class Program
    {
        static void Main(string[] args)
        {
            
            Car car = new Car("My car");

            car.Start();
            Console.WriteLine(car.Getname());
            Console.ReadLine();
        }
    }
}

Output:

Car started!
My Car

No comments:

Post a Comment