0

I created a template object with a back end CS that looks like this:

public partial class GridTemplate : StackLayout
{
    public event EventHandler Action;

    public GridTemplate()
    {
        InitializeComponent();
    }

    public ICommand TapButtonPressed => new Command((object componentIdentifier) =>
    {
        this.Action?.Invoke(this, new EventArgs());
    });
}

I can create a new object for that in C# like this:

var cell = new GridTemplate
{
    BackgroundColor = Color.White,
    Text = row.Name,
    Label = "ABC",
 };

But I cannot assign an action within the { }

However I can do this:

cell.Action += openCategoriesPage;

Can someone explain why I cannot assign Action when I construct the object?

Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
  • 3
    You aren't "assigning an action", you are adding an EventHandler delegate to the event. The operator is `+=` which translates to `AddHandler` in VB.NET – Panagiotis Kanavos Aug 02 '18 at 10:22
  • 1
    Possible duplicate of [Assigning events in object initializer](https://stackoverflow.com/questions/3993601/assigning-events-in-object-initializer) – Crowcoder Aug 02 '18 at 10:32

1 Answers1

1

First of all you are not allowed to do something like:

var cell = new GridTemplate
{
    Label += "ABC"
};

Its the same as Label = Label + "ABS" - second Label does not exist yet as object is not constructed.

Regarding events they are just a way of encapsulation, what will be generate in the background when you do += is call to an add method, something like:

cell.Action += openCategoriesPage; will become
cell.addAction(openCategoriesPage)

And you cant call methods in your {} usage as object is still not constructed.

You can read more about Events in C# via CLR Book.

user007
  • 1,122
  • 1
  • 10
  • 30