Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the downsides of using Reflection to create a Generic Type Command in my ViewModel?

I have a data object that has many different List properties. I want to use a single AddObject command instead of creating a different command for each List, so came up with the following code.

Is there any downsides you can see to using this? I thought performance might be slow, but I honestly haven't seen a difference.

public MyViewModel()
{ 
    _addCommand = new RelayCommand<IEnumerable>(AddGenericObject);

    // Old code.... defines an Add command per list
    // _addAddressCommand = new RelayCommand(() => AddObject<Address>(AddressList));
    // _addPhoneCommand = new RelayCommand(() => AddObject<Phone>(PhoneList));
    // ... etc
}

private void AddGenericObject(IEnumerable list)
{
    // Find Add Method
    var addMethod = this.GetType()
        .GetMethod("AddObject", BindingFlags.NonPublic | BindingFlags.Instance);

    // Created Generic Add Method
    Type genericType = list.GetType().GetGenericArguments()[0];
    var genericAddMethod = addMethod.MakeGenericMethod(genericType);

    // Invoke Method
    genericAddMethod.Invoke(this, new object[] { list });
}

private void AddObject<T>(EntityCollection<T> list)
   where T : EntityObject, new()
{
    var newItem = new T();
    list.Add(newItem);
}

It is used in the XAML by something like this:

<Button Content="New Address" 
        Command="{Binding AddCommand}"
        CommandParameter="{Binding AddressList}" />

<Button Content="New Phone" 
        Command="{Binding AddCommand}"
        CommandParameter="{Binding PhoneList}" />
like image 474
Rachel Avatar asked Jan 19 '26 16:01

Rachel


2 Answers

In one word - performance, but before you rid of the code benchmark it - it might be fast enough for your needs.

like image 171
Dror Helper Avatar answered Jan 21 '26 07:01

Dror Helper


Performance is always the biggest factor when considering the use of reflection. In general, you should try to avoid using reflection if you can.

like image 39
James Johnson Avatar answered Jan 21 '26 07:01

James Johnson