Home > Enterprise >  How to quickly cast an object in lambda in C#
How to quickly cast an object in lambda in C#

Time:07-08

I find out I have to cast things very often.

    Button.MouseMove  = (s, e) =>
    {
        Drawable d = s as Drawable;
        d.Cursor = Cursors.Pointer;
    };

How do I reduce these three lines into one line like this??

    Button.MouseMove  = (s, e) => s.Cursor = Cursors.Pointer where s as Drawable; //an example of how i want to simplify the code
        

CodePudding user response:

This works with at least C# 7.1:

Button.MouseMove  = (s, e) => _ = s is Drawable d ? d.Cursor = Cursors.Pointer : default;
  •  Tags:  
  • c#
  • Related