Reputation: 3529
I have two custom objects, lets say Cat
and Dog
. I want to create an observable collection
that can hold either of these objects, as they are very similar. Can I use base classes to do this?
If so, would you mind providing a quick example.
And if I do use a base class, does that mean if I want to use common fields, I should put those into the base class?
EDIT: I'm hoping to then bind a WPF datagrid to the properties of these objects. I don't know if it's possible to bind a datagrid in WPF to two different kind of objects...
Upvotes: 0
Views: 551
Reputation: 468
Yes, in that case you can use a base class:
public class Pet
{
public int Id { get; set; }
public string Name { get; set; }
public void Run() { }
}
public class Cat: Pet
{
public string Meow()
{
return "Meow";
}
}
public class Dog :Pet
{
public string Bark()
{
return "Whow";
}
}
Notice however, that when you place instances of both classes in one collection you can access only members of the base class. So this code is valid:
var collection = new ObservableCollection<Pet> {new Cat(), new Dog()};
foreach (var pet in collection)
{
pet.Run();
}
but you cannot use methods Meow() and Bark() unless you use explicit casting.
Be careful with moving too many members to the base class - in the example above Meow() doesn't make sense for the Dog and Bark() for the Cat. If you need to use some method specific to the derived class you could check the type with:
pet.GetType()
and then cast object to the derived type:
var cat = (Cat)pet;
cat.Meow();
Upvotes: 5
Reputation: 2293
Yes to the properties, that's sort of the point of base classes. You express the commonality in the base and the specificity in the derived classes. As for whether the base class is the best place for an observable collection, well, it depends. You need to give some more insight into the need and the expected usage. It's doable though.
Check out ObservableCollection<T> also.
Upvotes: 0
Reputation: 8531
Yes. You can use a base class say animal. And yes if they have common fields such as name, type, etc.. they can go in there.
class Animal {
public String name;
}
Then just extend that. But you can also extend the functionality.
class Dog extends Animal {
public void bark();
}
Now anything that asks for something of type Animal can receive Dog.
public void addToCollection(Animal animal)
addToCollection(new Dog());
This is actually the backbone for Java's Object.
Upvotes: 1