Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create method with params ref T parameter

Tags:

c#

c#-4.0

This is what I've got in a project including fairly complex cases of reflection:

static int PopulateValues<T>(List<string> propertyNames, ref T list) { /*...*/ }

// Example call:
PopulateValues(propertyNames, ref list1);

I'd really like to add params along and do params ref T[] lists to allow usage:

PopulateValues(propertyNames, ref list1, ref list2, ...);

However, this gives me the following error:

Parameter cannot have both 'params' and 'ref' modifiers.

My initial thought was letting list be an object[], but the usage would be ugly (casting object). So for now, I'm calling the method one time for each type, doing unnecessary multiple enumerations.

SOLVED: I don't need ref for calling reflection methods on parameter class (SetValue, GetValue, InvokeMember etc), which means that I can skip the ref altogether. Really, I should have tried that.

like image 942
Simeon Avatar asked Jul 17 '26 16:07

Simeon


1 Answers

On ref + params:

A member can't be a reference. And since params transforms each parameter into array member this isn't possible.

The only thing I can think of is manually creating a number of overloads.


But in your case I don't see why you need ref in the first place. To add members to a list you don't need to change the reference itself, and thus don't need to pass it my ref in the first place.

like image 86
CodesInChaos Avatar answered Jul 19 '26 06:07

CodesInChaos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!