Álvaro García
Álvaro García

Reputation: 19386

((MyCustomObject)myObjectType).MyProperty has a huge cost?

Well, I have in my model an ObservableCollection of type object in this way:

private ObservableCollection<object> _selectedItems = new ObservableCollection<object>();
public SelectedItems
{
    get{return _selectedItems}
    set
    {
        _selectedItems = value;
        NotifyPropertyChanged("SelectedItems");
    }
}

I am using a attached property to update the selected items from the view, so to do it a generic behavior that use the object type.

Well, my problem is that in my view model I need to access of the properties of my type. So I am doing this:

((MyCustomType)SelectedItems[0]).MyProperty.

But this is a very tedious work and think that this cast has a cost. So I am doing this many times, I am wondering if there is a better solution.

Perhaps to use a dynamic type instead of a object type? The advantage is that I don't need to do the cast, but I lost the intellisense feature, so it is more difficult to debug errors.

Perhaps another solution?

Upvotes: 0

Views: 44

Answers (1)

Jamiec
Jamiec

Reputation: 136154

Casting without boxing/unboxing (So assuming MyCustomObject is a class not a struct) does not have a particularly huge overhead, but the correct solution if you know that the type is always MyCustomObject is to declare the collection as

private ObservableCollection<MyCustomObject> _selectedItems 
                        = new ObservableCollection<MyCustomObject>();

Upvotes: 2

Related Questions