blah blah blah is here! blah blah » Close

up1down
link

How can I do the following using a inherited class?

Thanks
Jeff

namespace question
{
public class Dog
{
public string Breed { get; set; }
}

public class Dogs : List<Dog>
{


}

public class DoSomething
{
public static void HereWeGo()
{
Dog _brutus = new Dog();
Dog _rex = new Dog();

_brutus.Breed = "Basset Hound";
_rex.Breed = "Basset Hound";

Dogs _allDogs = new Dogs();
Dogs _allFoundDogs = new Dogs();

///this line here generates a compile time error because the .FindAll returns a
///List<Dog> not a collection Dogs. How can I use the list operations whilst using an inherited
///class please?
_allFoundDogs = _allDogs.FindAll(p => p.Breed == "Basset Hound");
}
}

}

last answered one year ago

1 answers

link

You' ll need to introduce a constructor in the Dogs class which calls the base class constructor. Here's one way you could do that:

using System;
using System.Collections.Generic;

namespace question
{
public class Dog
{
public string Breed { get; set; }

public string Name { get; set; }
}

public class Dogs : List<Dog>
{
public Dogs(params Dog[] dogs) : base (dogs)
{

}
}

public class DoSomething
{
public static void HereWeGo()
{
Dog _brutus = new Dog();
Dog _rex = new Dog();

_brutus.Breed = "Basset Hound";
_brutus.Name = "Brutus";
_rex.Breed = "Basset Hound";
_rex.Name = "Rex";

Dogs _allDogs = new Dogs(_brutus, _rex);
// EDITED to remove superfluous lines
Dogs _allFoundDogs = new Dogs(_allDogs.FindAll(p => p.Breed == "Basset Hound").ToArray());
foreach(Dog dog in _allFoundDogs) Console.WriteLine(dog.Name);
}

static void Main()
{
HereWeGo();
Console.ReadKey();
}
}
}

Hi Vulpes, Thanks for that. As usual, the answer is obvious once you pointed it out. How did you get your post to have the colors and indenting like that? Thanks again. Jeff

I have added the following constructor. public Dogs(IEnumerable<Dog> collection) : base(collection) { } Thanks again Jeff

vulpes
17279

For syntax highlighting etc. just place your code within [code] ... [/code] tags. This only works though in questions/answers, not in comments. It also doesn't work properly in IE8 (all blank lines seem to get removed, at least on my machine). So it's best to use FireFox or Chrome when accessing this site.

vulpes
17279

Yes, it's a good idea to use IEnumerable<Dog> as the constructor parameter type so you don't have to call the ToArray() method when using a List<Dog> or LINQ query to populate a Dogs instance.

Feedback