I have a piece of code that is like this:
void someAlgorithm(SomeType someVar)
{
someVar.someMember = createSomeValue();
lock(something)
{
SomeType someOtherVar = something.Find(someVar.unrelatedMember);
if(someOtherVar != null)
someOtherVar.someMember = someVar.someMember;
}
}
(I needed to adapt it a bit for posting, so please bear with me if I messed it up in doing so.)
Now I need this exact piece of code for another member of someVar
(which has a related, but different type) and another creation function. I know I can just take this code, copy it, replace a few identifiers, and be done. But I feel dirty doing so. I feel there should be a way to generalize this little algorithm.
I know I can always pass the creation function as a delegate, but I don't know how to generalize the member access and then there's the issue of those members (and creation functions) having different types.
In C++, I would use member pointers combined with templates for doing this. Member pointers aren't exactly a piece of cake to use, but once I had looked up their weird syntax, I'd be done within a few minutes. How to do that in C#?
Edit: Since this doesn't seem clear enough, here's what that other instance of the same algorithm looks like:
void someOtherAlgorithm(SomeOtherType someVar) // 1 change here
{
someVar.someOtherMember = createSomeOtherValue(); // 2 changes here
lock(something)
{
SomeOtherType someOtherVar = something.Find(someVar.unrelatedMember);
if(someOtherVar != null)
someOtherVar.someOtherMember = someVar.someOtherMember; // 2 changes here
}
}
I hope this clarifies this.