C# passing a list of strongly typed property names
Asked Answered
C

1

6

I'm looking for a way to pass in a list of strongly typed property names into a method that I can then dissect and get the properties that the caller is interested in. The reason I want to do this is to have a copy method that only copies the fields the user specifies. Right now, the method takes a list of strings to use with the Getvalues and get properties methods in reflection, but I want to guard against refactoring of properties and the strings not being updated by the developer.

I found this article Here, but unfortunately, it does not do a list. I can do something like:

public static void Copy(Expression<Func<TObject>> propertiesToCopy )
{
}

And then have the caller do

PropertyCopier<List<string>>.Copy(() => data);

But then I have to specify how many properties the caller can have like this:

public static void Copy(Expression<Func<TObject>> propertiesToCopy,Expression<Func<TObject>> propertiesToCopy2, Expression<Func<TObject>> propertiesToCopy3 )
{
}

This would allow for three properties. Is there anyway to add it to a List or Queryable<> to allow as many properties as the caller wants? I tried using the Add in List and having the Expression

Thanks in advance

Edit: I did find a few articles this evening that refer to using the C# param keyword to accomplish this. Are there any better or more efficient ways, or is this the best way to do it?

Cell answered 11/6, 2013 at 11:11 Comment(5)
Are you doing type-mapping with this? If so, you might want to look at AutoMapperMinded
What is wrong with List<Func<Object>> propertiesToCopy?Parabasis
Take a look at Get Custom Attributes from Lambda Property ExpressionCragsman
Andrei, I believe when I tried that, using the Add() method was not happy about adding them in, is this better than using the params?Cell
@MatthewWatson - I don't want to use something that does it for me. I am trying to use as little third party stuff on this particular project.Cell
B
13

Use the params keyword to define a method that takes a variable number of arguments:

public static void PrintPropertyNames<T>(params Expression<Func<T, object>>[] properties)
{
    foreach (var p in properties)
    {
        var expression = (MemberExpression)((UnaryExpression)p.Body).Operand;
        string memberName = expression.Member.Name;
        Console.WriteLine(memberName);
    }
}

For instance, you could call the PrintPropertyNames method passing two expressions:

PrintPropertyNames<FileInfo>(f => f.Attributes, f => f.CreationTime);

This example displays the following output to the console:

Attributes
CreationTime
Brawley answered 11/6, 2013 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.