using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace half_test {
class Car {
private int printInfo;
public int PrintInfoMethod {
get {
return printInfo;
}
set {
printInfo=value;
}
}
public void Car() {
Console.WriteLine("<" + printInfo);
}
}
class Engine {
static void Main(string[] args) {
Engine blf=new Engine("BLF", 1597);
Engine bny=new Engine("BVY", 1984);
Engine blg=new Engine("BLG", 1389);
Car[] cars=new Car[4];
cars[0]=new Car("GOLF E", blf);
cars[1]=new Car("GOLF E", blf);
cars[2]=new Car("GOLF E", blf);
cars[3]=new Car("GOLF E", blf);
foreach (Car car in cars) car.printInfo();
}
}
}
this error point.
why error?
When I compile the above code I get this error:
Error: 'Car': member names cannot be the same as their enclosing type
Why? How can I resolve this?
I want view this screenshat. enter image description here
Why?
That's just the rules of the language. If you're creating a class called Car
, it can't contain any members (properties, methods, fields, nested types, events) called Car
. It would be really confusing if this were allowed, IMO.
How can I resolve this?
By renaming your method. At the moment it's called Car()
, which doesn't describe what it does. How about calling it PrintInfo
? It's not clear why you've got a property called PrintInfoMethod
either... or why you're calling constructors that don't exist in the code you've shown.
If you want a Car
to have some sort of descriptive text, I'd call that Description
, and if you really want a method to print that description, give it an appropriate name. Example:
class Car
{
public string Description { get; set; }
public void PrintDescription()
{
Console.WriteLine($"< {Description}");
}
}
See more on this question at Stackoverflow