Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write typical C# one-liners as separate pieces of code?

I’m taking over a Prism-based C# application that contains quite some lambda-ish one-liners, like the following:

using Prism.Interactivity.InteractionRequest;
...
public InteractionRequest<Confirmation> OwnObjectRequest { get; } = new InteractionRequest<Confirmation>();
...
OwnObjectRequest.Raise(confirmation, c => // one-liner
{
    Confirmation conf = (Confirmation)c;
    if (conf.Confirmed)
    {
        DoSomething();
    }
});

I would like to program in a cleaner way, by which I mean that I only want to put one single action on one single line, but I don’t get it done (what’s the signature of some_Method, how to use it in order to define an action, …?)
This is what I have until now:

public ... some_Method(...)
{
    Confirmation conf = (Confirmation)c;
    if (conf.Confirmed)
    {
        DoSomething();
    }
}

Action actionToPerform = new Action(some_Method);
OwnObjectRequest.Raise(confirmation, actionToPerform);

Does anybody know how to write this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I don’t think there’s any technical advantage in writing such a one-liner in multiline format, but it would heavily help me understand how to read, understand and maybe give support for this source code.

>Solution :

I’m not sure if I understood correctly or not, but you can define a separate method or use a lambda expression directly

so for example if you want separate mtehod :

public void HandleConfirmation(Confirmation confirmation)
{
    if (confirmation.Confirmed)
    {
        DoSomething();
    }
}

and then, you can use this method as the action to be raised:

OwnObjectRequest.Raise(confirmation, HandleConfirmation);

or using a lambda expression

OwnObjectRequest.Raise(confirmation, c =>
{
    Confirmation conf = (Confirmation)c;
    if (conf.Confirmed)
    {
        DoSomething();
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading