Hi,
I'm trying things in OOP. I have three questions:
1) what should I give as parameter in the line Console.Write(hfd.Prod("Apple", 5)) ? (error: no overload method takes 2 arguments)
2) Console.Write(Prod("Apple", 5)); same error => is line Head hfd = new Head(); then unnecessary? Can i access method Prod directly from Main?
3) Apparently, the line Product obj= new Product(); is not necessary. Why?
Thanks
V
public class Product
{
public string Name { get; set; }
public int Price { get; set; }
}
public class Head
{
static void Main(string[] args)
{
Head hfd = new Head();
Console.Write(hfd.Prod("Apple", 5));
// Console.Write(Prod("Apple", 5)); this gives the same error => no reference to class Head needed?
}
public void Prod(Product p)
{
//Product obj= new Product(); why not necessary?
if (p.Price > 0)
Console.WriteLine("ok");
}
}
Aymen AmriPosted Aug 16, 2022, 9:53 AM
Hello Valérie
I think there is a few points to consider in your code before answering your question.
You have a static void main in a class called Head the you instanciate during the execution of main. I think this is not the best way to do things.
You should call your main class Program.cs and add the main in it with the method that you want to call
Now to answer your question :
1) what should I give as parameter in the line Console.Write(hfd.Prod("Apple", 5)) ? (error: no overload method takes 2 arguments)
Here you are passing two parameters : The first one is string the second one is int, if your method was Prod(string name, int price) then it would be accepted but here you have Prod(Product p) so you need to pass an instanciated product to your method (see line 5 of my code)
2) Console.Write(Prod("Apple", 5)); same error => is line Head hfd = new Head(); then unnecessary? Can i access method Prod directly from Main?
As mentionned at the beginning, try always to define your classes outside of the main class to have a good seperation of concern.
3) Apparently, the line Product obj= new Product(); is not necessary. Why?
Yes here it's not necessary, because you are passing the product as parameter, and here by this intruction you will reinstanciate the object and then you will loose the values of the product that you are passing.
Valerie MeunierPosted Aug 18, 2022, 8:21 AM