I’m learning C# from a book and i’m expanding on an example in an effort to better understand the syntax.
I’m trying to use the following code to cycle through a collection of objects and pick out only certain ones so I can load them into a separate array. I’m struggling with this particular line right now:
if (animalCollection[i].Equals(Chicken))
Here is the complete code for Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch11Ex02
{
class Program
{
static void Main(string[] args)
{
Animals animalCollection = new Animals();
animalCollection.Add(new Cow("Jack"));
animalCollection.Add(new Chicken("Vera"));
animalCollection.Add(new Chicken("Sally"));
Animal[] birds = new Animal[2];
for (int i = 0; i < animalCollection.Count; i++)
{
if (animalCollection[i].Equals(Chicken))
birds[i] = animalCollection[i];
}
foreach (Animal myAnimal in animalCollection)
{
myAnimal.Feed();
}
Console.ReadKey();
}
}
}
My goal is to load only object types Chicken into a new array called birds.
here is the code for class Animal:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch11Ex02
{
public abstract class Animal
{
protected string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public Animal()
{
name = "The animal with no name";
}
public Animal(string newName)
{
name = newName;
}
public void Feed()
{
Console.WriteLine("{0} has been fed." , name);
}
internal bool equals()
{
throw new NotImplementedException();
}
}
}
and here is the code for class Chicken:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch11Ex02
{
public class Chicken : Animal
{
public void LayEgg()
{
Console.WriteLine("{0} has laid an egg." , name);
}
public Chicken(string newName): base(newName)
{
}
}
}
and here is the code for class Animals:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ch11Ex02
{
public class Animals : CollectionBase
{
public void Add(Animal newAnimal)
{
List.Add(newAnimal);
}
public void Remove(Animal newAnimal)
{
List.Remove(newAnimal);
}
public Animals()
{
}
public Animal this[int animalIndex]
{
get
{
return (Animal)List[animalIndex];
}
set
{
List[animalIndex] = value;
}
}
}
}
Fundamentals
To determine whether an object is of a given type, you can use
typeoforisor
so specifically in your case
becomes
or
You can also determine an object’s type like this
The Fast Way
Now that I have covered how this works at a basic level, here’s a way to accomplish the same in one line, using Linq
By the Way
If you then wanted to get the type name as a string, you could do this