I have a c# question that im struggling with. I am designing a class but im not familiar with oop too much. Is it possible to define a list of the same type as the type of the class itself? For example say i have a dog class:
public class Dog
{
public string _name {get; set;};
public Dog (string, name)
{
_name = name;
}
public List<Dog> listOfDogs ()
{
// blah blah
}
}
Is such a structure possible? if so, how? Is it the proper way to do something like this? Or should i create another helper class that simply does the building of the list of dogs by creating separate dog objects?
Thanks
Short answert: Yes, it is.
This makes sense in many cases. A
Dogcould be associated to other dogs in an OOP world.Besides, let me just suggest you a few other tiny improvements:
Especially the interface thing is worth a lot of reading if you are new to OOP. There are a few different list implementations, and OOP helps you to hide these so-called “implementation details”. Later on you could use a
Dog[]instead of aList<Dog>without changing consumers of your class. Both do implementIList<Dog>.It’s stuff that is described in detail in many places. There are books, articles, or this question on SO: What do programmers mean when they say, "Code against an interface, not an object."?