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);
}
}
}
>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);