I'm new to C# programming and have hit a snag I cannot get past.
I'm getting this compile error:
CS0305: Using the generic type 'System.Collections.Generic.IEnumerable' reuires 1 type arguments
with this code;
class Program
{
static void Main(string[] args)
{
Car c = new Car();
c.PetName = "Frank";
c.Speed = 55;
c.colour = "Green";
Console.WriteLine("Name = : {0}", c.PetName);
c.DisplayStats();
Garage carLot = new Garage();
// Hand over each car in the collection
foreach (Car c in carLot)
{
Console.WriteLine("{0} is going {1} MPH",
c.PetName, c.CurrentSpeed);
}
Console.ReadLine();
}
class Car
{
//Automatic Properties
public string PetName { get; set; }
public int Speed { get; set; }
public string colour { get; set; }
public void DisplayStats()
{
Console.WriteLine("Car Name: {0}", PetName);
Console.WriteLine("Speed: {0}", Speed);
Console.WriteLine("Color: {0}", colour);
}
}
public class Garage
{
private Car[] CarArray = new Car[4];
// Fill with some car objects on startup.
public Garage()
{
carArray[0] = new Car("Rusty", 30);
carArray[1] = new Car("Clunker", 55);
carArray[2] = new Car("Zippy", 30);
carArray[3] = new Car("Fred", 30);
}
}
public IEnumerator GetEnumerator()
{
foreach (Car c in carArray)
{
yield return c;
}
}
}
How can I resolve this?
There are two variants of IEnumerable, the generic one (which is in the System.Collections.Generic namespace) accepts a type argument which specified the types of objects that the enumerable contains. The other one (contained in the System.Collections namespace) has no type argument and so exposes the type object - you appear to be declaring / using the non-generic variant, however are not using the System.Collections namespace.
I think the quick way to fix your particular compile error is to put the following at the top of your source code file:
using System.Collections;
Alternatively you can instead use the Generic version (which you should try to do wherever possible as it is type safe) by specifying type parameters when you declare IEnumerable, like this:
IEnumerable<Car>
IEnumerator<Car>
You might also want to read An Introduction to C# Generics
You also seem to have a few more errors than that, but these seem like they might be from problems copying and pasting the source (specifically Garage does not implement IEnumerable, either the generic or non-generic version, and GetEnumerator is on the Program class, not the Garage class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With