What is the shortest possible way of coding in C# where an action is performed on an object (Properties updated or Methods called etc) and is returned in a code block? Note, this will be used for small code actions, for example updating 1 or 3 properties.
Is there some way of using anonymous functions, Lambda, Action etc to make the code as small as possible? A kind of Fluent style. This will be mainly used as part of larger Lambdas.
The length of identifier names is not important, the shortest code construct is. Example here not really significant, only that ANY object needs to have 1 or 2 properties updated before being passed into to another Method call.
Example I wish to do this:
public class Test2
{
void Display(Person p) => Console.Write(p.Name);
//intentionally this will not compile, what is the least code to update p and return p.
void ToAdultAndDisplay_XX(Person p){Display(p.Age = 21);}
//using extension method
void ToAdultAndDisplay_1(Person p) => Display(p.ActionOnSelf(i => i.Age = 21));
//standard
void ToAdultAndDisplay_2(Person p)
{
p.Age = 21;
Display(p);
}
}
Note the Person object needs to be updated and returned, so that it can be passed into a method, all inline.
The following example below makes use of an Extension method ActionOnSelf
that simply allows any object (in this example Person
) to update itself via a Lambda.
void ToAdultAndDisplay_1(Person p) => Display(p.ActionOnSelf(i => i.Age = 21));
Questions:
Does the code using
ActionOnSelf
use less code constructs vs any other code block, especially if updating a single property?Are there significant performance penalties using
ActionOnSelf
?Any alternative ways to perform this with the shortest amount of code?
The extension method is shown below:
using System;
namespace DevTestPlayground.ForStackOverflowExamples
{
public static class LambdaExtensions
{
public static T ActionOnSelf<T>(this T o, Action<T> action)
{
action.Invoke(o);
return o;
}
public static T ActionOnSelf<T>(this T o, params Action<T>[] actions)
{
foreach (Action<T> f in actions) f.Invoke(o);
return o;
}
}
}