Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a new object in C#

So I have created a car class with objects and constructor and I’m trying to get the values but I’m getting an error which says: There is no argument given that corresponds to the required formal parameter c#
This is my class:

public class Car
    {
        private int yearOfProduction;
        private int engineVolume;

        public Car(int yearOfProduction, int engineVolume)
        {
            this.yearOfProduction = yearOfProduction;
            this.engineVolume = engineVolume;
        }

        public int YearOfProduction { get; set; }
    
        public int EngineVolume { get; set; }
    }
}

And my main method:

using System;

namespace Car2
{
    class Program
    {
        static void Main()
        {
            Car car = new Car();
            Console.Write("Year of production: ");
            car.YearOfProduction = int.Parse(Console.ReadLine());
            Console.Write("Engine volume: ");
            car.EngineVolume = int.Parse(Console.ReadLine());
            Console.WriteLine(YearOfProduction);
            Console.WriteLine(EngineVolume);
        }
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’ve got a few different issues here.

Starting with the Car class:

You only have one constructor, no default constructor to hit with new Car(). Adjust your class to something like this:

public class Car
{
    private int yearOfProduction;
    private int engineVolume;

    public Car(int yearOfProduction, int engineVolume)
    {
        this.yearOfProduction = yearOfProduction;
        this.engineVolume = engineVolume;
    }

    public Car() //this is what will be called on new Car()
    {

    }

    public int YearOfProduction { get; set; }

    public int EngineVolume { get; set; }
}

You can otherwise leave the class as is by calling the constructor you provided, which requires two ints, like Car car = new Car(5, 5).

In your Main, the lines

Console.WriteLine(YearOfProduction);
Console.WriteLine(EngineVolume);

Are not referring to the properties of car. You need to adjust that to:

Console.WriteLine(car.YearOfProduction);
Console.WriteLine(car.EngineVolume);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading