Reputation: 63
What would be a simple way to pass a parameter to a class constructor when it's a collection of that class?
I'm thinking I need to derive from ObservableCollection to accommodate the parameter, but not sure what the best way is to do that.
// constructor
class MyClass(object myParam)
{
// do something here
}
// usage
Items = new ObservableCollection<MyClass>(); // How do I pass myParam?
Upvotes: 0
Views: 309
Reputation: 9804
It is entirely possible to write this:
public MyClass(MyClass[] myParam)
{
// do something here
}
The code of a class can use the class itself as a type. In native C++ you had to provide a prototype to do that, but by the time .NET came around the compilers were able to figure that part out.
If MyClass is a generic collection, this would be the code:
class MyClassCollection : List<MyClass>{
public MyClass(MyClass myParam){
// do something here
}
}
I have no idea why you think you that - of all the collection classes - you need to derive from ObservableCollection. You can derive from it, but there is nothing forcing you to pick it.
Upvotes: 0
Reputation: 450
It possible in the following ways
// class
class MyClass
{
// constructor
public MyClass(object myParam)
{
}
}
// make a object
object param = new object();
// pass param
var Items = new ObservableCollection<MyClass>(){new MyClass(param)};
Upvotes: 1
Reputation: 5523
Creating a collection does not allocate any objects of that class. When you do Items.Add(new MyClass(<argument>)
pass the arguments at that point.
Upvotes: 2