I'm developing an Android C# Application using Xamarin. It has a very simple structure: the MainActivity launches and creates instances of classes GUIHandler and Connection. Each class raises different events:
In Connection.cs:
public EventHandler<ConnectionEventArgs> ConnectionMade;
protected virtual void OnConnectionMade()
{
if (ConnectionMade != null) {
ConnectionMade (this, new ConnectionEventArgs ());
}
}
public EventHandler<ConnectionEventArgs> ConnectionFailed;
protected virtual void OnConnectionFailed()
{
if (ConnectionFailed != null) {
ConnectionFailed (this, new ConnectionEventArgs ());
}
}
public EventHandler<ConnectionEventArgs> LostConnection;
protected virtual void OnLostConnection()
{
if (LostConnection != null) {
LostConnection (this, new ConnectionEventArgs ());
}
}
public EventHandler<ConnectionEventArgs> ReceivedData;
protected virtual void OnReceivedData(byte[] _byteDataReceived, int _byteDataReceivedLength)
{
if (ReceivedData != null) {
ReceivedData (this, new ConnectionEventArgs {byteDataReceived = _byteDataReceived, byteDataReceivedLength = _byteDataReceivedLength});
}
}
public EventHandler<ConnectionEventArgs> SentData;
protected virtual void OnSentData()
{
if (SentData != null) {
SentData (this, new ConnectionEventArgs ());
}
}
In GUIHandler.cs:
public EventHandler<GUIHandlerEventArgs> SendButtonClicked;
protected virtual void OnSendButtonClicked()
{
if (SendButtonClicked != null) {
SendButtonClicked (this, new GUIHandlerEventArgs { sendTextEditData = sendEditText.Text });
}
}
The subscriptions are in the MainActivity.cs file, which gets run when the application is executed:
...
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
var guiHandler = new GUIHandler();
var connection = new Connection();
connection.ConnectionMade += guiHandler.OnConnectionMade;
connection.ConnectionFailed += guiHandler.OnConnectionFailed;
connection.LostConnection += guiHandler.OnLostConnection;
connection.ReceivedData += guiHandler.OnReceivedData;
connection.SentData += guiHandler.OnSentData;
// THE CODE BELOW RAISES System.ArgumentException: Value does not fall within expected range DURING RUNTIME.
guiHandler.SendButtonClicked += connection.OnSendButtonClicked;
// However, this line makes the job.
guiHandler.SendButtonClicked += (sender, args) => connection.Send (args.sendTextEditData);
}
I can't find the reason why it raises that Exception there and does not anywhere else. However, doing some debugging I noticed I can't subscribe a public method from connection, but have no idea why. Anyone has any idea?
Edit: this is the definition of OnSendButtonClicked in Connection.cs:
public void OnSendButtonClicked (object sender, GUIHandlerEventArgs args)
{
//Send data
Send(args.sendTextEditData);
}