I am trying to make an event that gets raised when something happens. So other classes that contain a reference to the class that raised the event get notified.
This is what i have got so far:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DropArea : MonoBehaviour {
public event EventHandler ObjectChange;
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider other)
{
var correctType = FindParentWithComponent(other.gameObject);
if (correctType != null)
{
var cc = correctType.GetComponent<Object_properties>();
if(cc.VariableTypeSelector == AcceptedVariableType)
{
DetectedObjectChange(null); // here i want to raise the event
}
}
}
protected virtual void DetectedObjectChange(EventArgs e)
{
EventHandler handler = ObjectChange;
if (handler != null)
{
handler(this, e );
}
}
}
this is the class that should get notified by the raised event:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IfStatement : MonoBehaviour {
public DropArea Base, Check, Increment;
void Start()
{
Base.ObjectChange += OnBaseObjectChange; //this line gives me an error so i cant compile.
}
// Update is called once per frame
void Update () {
}
void OnBaseObjectChange(System.Object sender)
{
Debug.Log("event is raised by element");
}
}
this is the error i get :
No overload for 'OnBaseObjectChange' matches delegate 'EventHandler'
I have never worked with events before but i cant really understand how to fix this. Sadly i also dont really understand the microsoft docs about events :(
If extra clarification is needed pls let me know!
All help is really appreaciated!
Just change this method. Because your event also requires EventArgs
void OnBaseObjectChange(System.Object sender, EventArgs e)
{
Debug.Log("event is raised by element");
}
Delegates hold signatures of methods. As you can see your event has a method type with two parameters. Trying to use it with a single parameter causes the error.
handler(this, e);
Alternatively, you can change the type of your event to something else. For example an Action<System.Object> to keep the current signature of your handler method, if you don't want to have an EventArgs in your event:
public event System.Action<System.Object> ObjectChange;
void OnBaseObjectChange(System.Object sender)
{
Debug.Log("event is raised by element");
}
Where you can call it like:
handler(this);
Related
I have 2 C# classes one of them has a string delegate and the other subscribes an function to that delegate.
My question is I want to combine the two called string functions from the delegate instead of choosing the return value between them randomly
delgatesystem.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class delegatesystem : MonoBehaviour {
public delegate string MyDelegate();
public static event MyDelegate MyEvent;
string GameObjectsNames = "";
void Update ()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (MyEvent != null)
{
GameObjectsNames += MyEvent();
}
}
}
}
delegatesave.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class delegatesave : MonoBehaviour {
void Start ()
{
delegatesystem.MyEvent += DelegateFunction;
}
string DelegateFunction()
{
return gameObject.name;
}
}
note: the delgatesave.cs is attached to 2 gameobjects.
First of all, creating events with non-void delegates is an antipattern. Events are typically used with potentially more subscribers.
If a non-void multicast delegate is invoked with multiple subscribers, always the return value of the last subscribed method is returned.
But after all you can do something like this:
string[] objectNames = MyEvent.GetInvocationList().Cast<MyDelegate>().Select(del => del()).ToArray();
However, a better solution would be to use more conventional events:
public class PopulateNamesEventArgs : EventArgs
{
private List<string> names = new List<string>();
public string[] Names => names.ToArray();
public void AddName(string name) => names.Add(name);
}
And then in your class:
public event EventHandler<PopulateNamesEventArgs> MyEvent;
protected virtual void OnMyEvent(PopulateNamesEventArgs e) => MyEvent?.Invoke(this, e);
Invokation:
var e = new PopulateNamesEventArgs();
OnMyEvent(e);
string[] objectNames = e.Names; // the result is now populated by the subscribers
Subscription:
void Start()
{
delegatesystem.MyEvent += DelegateFunction;
}
void DelegateFunction(object sender, PopulateNamesEventArgs e)
{
e.AddName(gameObject.name);
}
I have to access data from an event in another class.
In that class things are like this:
namespace MavLink
{
public class Mavlink
{
...
public event PacketReceivedEventHandler PacketReceived;
...
private void ProcessPacketBytes(byte[] packetBytes, byte rxPacketSequence)
{
...
if (PacketReceived != null)
{
PacketReceived(this, packet);
}
...
}
}
public delegate void PacketReceivedEventHandler(object sender, MavlinkPacket e);
}
And in the main I've tried to do like this:
...
m.ParseBytes(newlyReceived);
m.PacketReceived += (sender, e) => {
Console.WriteLine(e.SystemId);
Console.WriteLine(e.ComponentId);
Console.WriteLine(e.SequenceNumber);
Console.WriteLine(e.TimeStamp);
Console.WriteLine(e.Message);
};
But it doesn't seem work.
Thank you for your help.
Edit:
It compiles without errore but nothing is printed on the console. I don't know how to check if the event has been rised though.
Well on this what I read I have created a usual Event that will give you some data to access.
We start with creating the event.
public delegate void PacketReceivedEventHandler(var pPacket);
public event PacketReceivedEventHandler PacketReceived;
I put a var in there cause I didn't exactly saw what you are "delivering". Just change it into whatever you need.
So, lets continue. Place this when the Event needs to be triggered.
if (Mavlink.PacketReceived != null)
Mavlink.PacketReceived(YourPackage);
YourPackage is whatever you want to deliver.
But you need to subscribe a event to do stuff with it.
Mavlink.PacketReceived += Mavlink_PacketReceived;
C# usually created a class if you double tab after the +=. But here is the class I created.
private void Mavlink_PacketReceived(var pPacket)
{
if(pPacket != null)
{
Console.WriteLine(pPacket.SystemId);
Console.WriteLine(pPacket.ComponentId);
Console.WriteLine(pPacket.SequenceNumber);
Console.WriteLine(pPacket.TimeStamp);
Console.WriteLine(pPacket.Message);
}
}
I dont know what comes after that in your code, but make sure that there will be something to make you command line wait so it wont close after firing that.
I made an example, which works fine, hope it helps. Replace EventHandler by your PacketRecievedEventHandler:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var sender = new Sender();
var reciever = new Reciever(sender);
sender.ProcessPacketBytes(null, byte.MaxValue);
Console.ReadLine();
}
}
/// <summary></summary>
public class Sender
{
private readonly object _objectLock = new object();
public event EventHandler PacketReceived
{
add
{
lock (_objectLock)
{
PacketRecievedEvent += value;
}
}
remove
{
lock (_objectLock)
{
PacketRecievedEvent -= value;
}
}
}
private event EventHandler PacketRecievedEvent;
public void ProcessPacketBytes(byte[] packetBytes, byte rxPacketSequence)
{
EventHandler handler = this.PacketRecievedEvent;
if (handler != null)
{
handler(this, new EventArgs());
}
}
}
public class Reciever
{
public Reciever(Sender sendertest)
{
sendertest.PacketReceived += (sender, e) =>
{ Console.WriteLine(e.GetType()); };
}
}
}
I have searched about the use of event syntax and its importance in c# code. So I found these advantages :
An event cannot be directly assigned ( we don't have the risk of someone removing all previous subscriptions, as with delegate syntax
No outside users can raise the event
I write this snippet to more understand these points above :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace certiflibrary
{
public class Class1
{
public static void Main()
{
Pub p = new Pub();
p.OnChange += () => Console.WriteLine("First");
p.OnChange += () => Console.WriteLine("Second");
p.OnChange = () => Console.WriteLine("Third");
p.Raise();
Console.ReadKey();
Console.WriteLine(p.OnChange.GetInvocationList().Length);
Console.ReadKey();
PubEvent pubevent = new PubEvent();
pubevent.OnchangeEvent += (sender, e) => Console.WriteLine("Event Raised: {0}",e.Name);
pubevent.Raise();
Console.ReadKey();
}
}
public class Pub
{
public Action OnChange { get; set; }
public void Raise()
{
if(OnChange != null)
{
OnChange();
}
}
}
public class PubEvent
{
public event EventHandler<SpecialArgs> OnchangeEvent = delegate { };
public void Raise()
{
OnchangeEvent(this, new SpecialArgs("hello"));
}
}
public class SpecialArgs:EventArgs
{
public SpecialArgs(string _name)
{
Name= _name;
}
public string Name { get; set; }
}
}
The first point is clear: I can not directly assign an event . But I don't understand the second one , even in my code I can access to the event from outside the class and raise it.
So, How can Event syntax prevent unwanted users to raise the event?
even in my code I can access to the event from outside the class and raise it
No, you can't.
You could call
p.OnChange()
since OnChange is a simple property, but you can not call
pubevent.OnchangeEvent()
since OnchangeEvent is an event.
The compiler would complain with
The event 'UserQuery.PubEvent.OnchangeEvent' can only appear on the left hand side of += or -= (except when used from within the type 'UserQuery.PubEvent')
So, you can call OnchangeEvent only from inside the PubEvent class, and that's exactly what you do in your Raise method. OnchangeEvent can't be raised from the outside.
You defined a method in your class that raises the event.
If this method is public anybody may call that method.
The event system prevents things like pubevent.OnchangeEvent(...)
I wish to create own events and dispatch them.
I never done this before in C#, only in Flex.. I guess there must be a lot of differencies.
Can anyone provide me a good example?
There is a pattern that is used in all library classes. It is recommended for your own classes too, especially for framework/library code. But nobody will stop you when you deviate or skip a few steps.
Here is a schematic based on the simplest event-delegate, System.Eventhandler.
// The delegate type. This one is already defined in the library, in the System namespace
// the `void (object, EventArgs)` signature is also the recommended pattern
public delegate void Eventhandler(object sender, Eventargs args);
// your publishing class
class Foo
{
public event EventHandler Changed; // the Event
protected virtual void OnChanged() // the Trigger method, called to raise the event
{
// make a copy to be more thread-safe
EventHandler handler = Changed;
if (handler != null)
{
// invoke the subscribed event-handler(s)
handler(this, EventArgs.Empty);
}
}
// an example of raising the event
void SomeMethod()
{
if (...) // on some condition
OnChanged(); // raise the event
}
}
And how to use it:
// your subscribing class
class Bar
{
public Bar()
{
Foo f = new Foo();
f.Changed += Foo_Changed; // Subscribe, using the short notation
}
// the handler must conform to the signature
void Foo_Changed(object sender, EventArgs args) // the Handler (reacts)
{
// the things Bar has to do when Foo changes
}
}
And when you have information to pass along:
class MyEventArgs : EventArgs // guideline: derive from EventArgs
{
public string Info { get; set; }
}
class Foo
{
public event EventHandler<MyEventArgs> Changed; // the Event
...
protected virtual void OnChanged(string info) // the Trigger
{
EventHandler handler = Changed; // make a copy to be more thread-safe
if (handler != null)
{
var args = new MyEventArgs(){Info = info}; // this part will vary
handler(this, args);
}
}
}
class Bar
{
void Foo_Changed(object sender, MyEventArgs args) // the Handler
{
string s = args.Info;
...
}
}
Update
Starting with C# 6 the calling code in the 'Trigger' method has become a lot easier, the null test can be shortened with the null-conditional operator ?. without making a copy while keeping thread-safety:
protected virtual void OnChanged(string info) // the Trigger
{
var args = new MyEventArgs{Info = info}; // this part will vary
Changed?.Invoke(this, args);
}
Events in C# use delegates.
public static event EventHandler<EventArgs> myEvent;
static void Main()
{
//add method to be called
myEvent += Handler;
//call all methods that have been added to the event
myEvent(this, EventArgs.Empty);
}
static void Handler(object sender, EventArgs args)
{
Console.WriteLine("Event Handled!");
}
Using the typical .NET event pattern, and assuming you don't need any special arguments in your event. Your typical event and dispatch pattern looks like this.
public class MyClassWithEvents
{
public event EventHandler MyEvent;
protected void OnMyEvent(object sender, EventArgs eventArgs)
{
if (MyEvent != null)
{
MyEvent(sender, eventArgs);
}
}
public void TriggerMyEvent()
{
OnMyEvent(sender, eventArgs);
}
}
Tying something into the event can be as simple as:
public class Program
{
public static void Main(string[] args)
{
MyClassWithEvents obj = new MyClassWithEvents();
obj.MyEvent += obj_myEvent;
}
private static void obj_myEvent(object sender, EventArgs e)
{
//Code called when my event is dispatched.
}
}
Take a look at the links on this MSDN page
Look into 'delegates'.
Define a delegate
Use the delegate type as field/property (adding the 'Event' keyword)
You are now exposing events that users can hook into with "+= MyEventMethod;"
Hope this helps,
I am currently having a hardtime understanding and implementing events in C# using delagates. I am used to the Java way of doing things:
Define an interface for a listener type which would contain a number of method definitions
Define adapter class for that interface to make things easier if I'm not interested in all the events defined in a listener
Define Add, Remove and Get[] methods in the class which raises the events
Define protected fire methods to do the dirty work of looping through the list of added listeners and calling the correct method
This I understand (and like!) - I know I could do this exactly the same in c#, but it seems that a new (better?) system is in place for c#. After reading countless tutorials explaining the use of delegates and events in c# I still am no closer to really understanding what is going on :S
In short, for the following methods how would I implement the event system in c#:
void computerStarted(Computer computer);
void computerStopped(Computer computer);
void computerReset(Computer computer);
void computerError(Computer computer, Exception error);
^ The above methods are taken from a Java application I once made which I'm trying to port over to c#.
Many many thanks!
You'd create four events, and methods to raise them, along with a new EventArgs-based class to indicate the error:
public class ExceptionEventArgs : EventArgs
{
private readonly Exception error;
public ExceptionEventArgs(Exception error)
{
this.error = error;
}
public Error
{
get { return error; }
}
}
public class Computer
{
public event EventHandler Started = delegate{};
public event EventHandler Stopped = delegate{};
public event EventHandler Reset = delegate{};
public event EventHandler<ExceptionEventArgs> Error = delegate{};
protected void OnStarted()
{
Started(this, EventArgs.Empty);
}
protected void OnStopped()
{
Stopped(this, EventArgs.Empty);
}
protected void OnReset()
{
Reset(this, EventArgs.Empty);
}
protected void OnError(Exception e)
{
Error(this, new ExceptionEventArgs(e));
}
}
Classes would then subscribe to the event using either a method or a an anonymous function:
someComputer.Started += StartEventHandler; // A method
someComputer.Stopped += delegate(object o, EventArgs e)
{
Console.WriteLine("{0} has started", o);
};
someComputer.Reset += (o, e) => Console.WriteLine("{0} has been reset");
A few things to note about the above:
The OnXXX methods are protected so that derived classes can raise the events. This isn't always necessary - do it as you see fit.
The delegate{} piece on each event declaration is just a trick to avoid having to do a null check. It's subscribing a no-op event handler to each event
The event declarations are field-like events. What's actually being created is both a variable and an event. Inside the class you see the variable; outside the class you see the event.
See my events/delegates article for much more detail on events.
You'll have to define a single delegate for that
public delegate void ComputerEvent(object sender, ComputerEventArgs e);
ComputerEventArgs would be defined like this:
public class ComputerEventArgs : EventArgs
{
// TODO wrap in properties
public Computer computer;
public Exception error;
public ComputerEventArgs(Computer aComputer, Exception anError)
{
computer = aComputer;
error = anError;
}
public ComputerEventArgs(Computer aComputer) : this(aComputer, null)
{
}
}
The class that fires the events would have these:
public YourClass
{
...
public event ComputerEvent ComputerStarted;
public event ComputerEvent ComputerStopped;
public event ComputerEvent ComputerReset;
public event ComputerEvent ComputerError;
...
}
This is how you assign handlers to the events:
YourClass obj = new YourClass();
obj.ComputerStarted += new ComputerEvent(your_computer_started_handler);
Your handler is:
private void ComputerStartedEventHandler(object sender, ComputerEventArgs e)
{
// do your thing.
}
The main difference is that in C# the events are not interface-based. Instead, the event publisher declares the delegate which you can think of as a function pointer (although not exactly the same :-)). The subscriber then implements the event prototype as a regular method and adds a new instance of the delegate to the event handler chain of the publisher. Read more about delegates and events.
You can also read short comparison of C# vs. Java events here.
First of all, there is a standard method signature in .Net that is typically used for events. The languages allow any sort of method signature at all to be used for events, and there are some experts who believe the convention is flawed (I mostly agree), but it is what it is and I will follow it for this example.
Create a class that will contain the event’s parameters (derived from EventArgs).
public class ComputerEventArgs : EventArgs
{
Computer computer;
// constructor, properties, etc.
}
Create a public event on the class that is to fire the event.
class ComputerEventGenerator // I picked a terrible name BTW.
{
public event EventHandler<ComputerEventArgs> ComputerStarted;
public event EventHandler<ComputerEventArgs> ComputerStopped;
public event EventHandler<ComputerEventArgs> ComputerReset;
...
}
Call the events.
class ComputerEventGenerator
{
...
private void OnComputerStarted(Computer computer)
{
EventHandler<ComputerEventArgs> temp = ComputerStarted;
if (temp != null) temp(this, new ComputerEventArgs(computer)); // replace "this" with null if the event is static
}
}
Attach a handler for the event.
void OnLoad()
{
ComputerEventGenerator computerEventGenerator = new ComputerEventGenerator();
computerEventGenerator.ComputerStarted += new EventHandler<ComputerEventArgs>(ComputerEventGenerator_ComputerStarted);
}
Create the handler you just attached (mostly by pressing the Tab key in VS).
private void ComputerEventGenerator_ComputerStarted(object sender, ComputerEventArgs args)
{
if (args.Computer.Name == "HAL9000")
ShutItDownNow(args.Computer);
}
Don't forget to detach the handler when you're done. (Forgetting to do this is the biggest source of memory leaks in C#!)
void OnClose()
{
ComputerEventGenerator.ComputerStarted -= ComputerEventGenerator_ComputerStarted;
}
And that's it!
EDIT: I honestly can't figure out why my numbered points all appear as "1." I hate computers.
there are several ways to do what you want. The most direct way would be to define delegates for each event in the hosting class, e.g.
public delegate void ComputerStartedDelegate(Computer computer);
protected event ComputerStartedDelegate ComputerStarted;
public void OnComputerStarted(Computer computer)
{
if (ComputerStarted != null)
{
ComputerStarted.Invoke(computer);
}
}
protected void someMethod()
{
//...
computer.Started = true; //or whatever
OnComputerStarted(computer);
//...
}
any object may 'listen' for this event simply by:
Computer comp = new Computer();
comp.ComputerStarted += new ComputerStartedDelegate(
this.ComputerStartedHandler);
protected void ComputerStartedHandler(Computer computer)
{
//do something
}
The 'recommended standard way' of doing this would be to define a subclass of EventArgs to hold the Computer (and old/new state and exception) value(s), reducing 4 delegates to one. In this case that would be a cleaner solution, esp. with an Enum for the computer states in case of later expansion. But the basic technique remains the same:
the delegate defines the signature/interface for the event handler/listener
the event data member is a list of 'listeners'
listeners are removed using the -= syntax instead of +=
In c# events are delegates. They behave in a similar way to a function pointer in C/C++ but are actual classes derived from System.Delegate.
In this case, create a custom EventArgs class to pass the Computer object.
public class ComputerEventArgs : EventArgs
{
private Computer _computer;
public ComputerEventArgs(Computer computer) {
_computer = computer;
}
public Computer Computer { get { return _computer; } }
}
Then expose the events from the producer:
public class ComputerEventProducer
{
public event EventHandler<ComputerEventArgs> Started;
public event EventHandler<ComputerEventArgs> Stopped;
public event EventHandler<ComputerEventArgs> Reset;
public event EventHandler<ComputerEventArgs> Error;
/*
// Invokes the Started event */
private void OnStarted(Computer computer) {
if( Started != null ) {
Started(this, new ComputerEventArgs(computer));
}
}
// Add OnStopped, OnReset and OnError
}
The consumer of the events then binds a handler function to each event on the consumer.
public class ComputerEventConsumer
{
public void ComputerEventConsumer(ComputerEventProducer producer) {
producer.Started += new EventHandler<ComputerEventArgs>(ComputerStarted);
// Add other event handlers
}
private void ComputerStarted(object sender, ComputerEventArgs e) {
}
}
When the ComputerEventProducer calls OnStarted the Started event is invoked which in turn will call the ComputerEventConsumer.ComputerStarted method.
The delegate declares a function signature, and when it's used as an event on a class it also acts as a collection of enlisted call targets. The += and -= syntax on an event is used to adding a target to the list.
Given the following delegates used as events:
// arguments for events
public class ComputerEventArgs : EventArgs
{
public Computer Computer { get; set; }
}
public class ComputerErrorEventArgs : ComputerEventArgs
{
public Exception Error { get; set; }
}
// delegates for events
public delegate void ComputerEventHandler(object sender, ComputerEventArgs e);
public delegate void ComputerErrorEventHandler(object sender, ComputerErrorEventArgs e);
// component that raises events
public class Thing
{
public event ComputerEventHandler Started;
public event ComputerEventHandler Stopped;
public event ComputerEventHandler Reset;
public event ComputerErrorEventHandler Error;
}
You would subscribe to those events with the following:
class Program
{
static void Main(string[] args)
{
var thing = new Thing();
thing.Started += thing_Started;
}
static void thing_Started(object sender, ComputerEventArgs e)
{
throw new NotImplementedException();
}
}
Although the arguments could be anything, the object sender and EventArgs e is a convention that's used very consistently. The += thing_started will first create an instance of the delegate pointing to target method, then add it to the event.
On the component itself you would typically add methods to fire the events:
public class Thing
{
public event ComputerEventHandler Started;
public void OnStarted(Computer computer)
{
if (Started != null)
Started(this, new ComputerEventArgs {Computer = computer});
}
}
You must test for null in case no delegates have been added to the event. When you make the method call however all delegates which have been added will be called. This is why for events the return type is void - there is no single return value - so to feed back information you would have properties on the EventArgs which the event handlers would alter.
Another refinement would be to use the generic EventHandler delegate rather than declaring a concrete delegate for each type of args.
public class Thing
{
public event EventHandler<ComputerEventArgs> Started;
public event EventHandler<ComputerEventArgs> Stopped;
public event EventHandler<ComputerEventArgs> Reset;
public event EventHandler<ComputerErrorEventArgs> Error;
}
Thank you all so much for your answers! Finally I'm starting to understand what is going on. Just one thing; It seems that if each event had a different number/type of arguments I'd need to create a different :: EventArgs class to deal with it:
public void computerStarted(Computer computer);
public void computerStopped(Computer computer);
public void computerReset(Computer computer);
public void breakPointHit(Computer computer, int breakpoint);
public void computerError(Computer computer, Exception exception);
This would require three classses to deal with the events!? (Well two custom, and one using the default EventArgs.Empty class)
Cheers!
Ok, FINAL clarification!: So this is pretty much the best I can do code-wise to implement those events?
public class Computer {
public event EventHandler Started;
public event EventHandler Stopped;
public event EventHandler Reset;
public event EventHandler<BreakPointEvent> BreakPointHit;
public event EventHandler<ExceptionEvent> Error;
public Computer() {
Started = delegate { };
Stopped = delegate { };
Reset = delegate { };
BreakPointHit = delegate { };
Error = delegate { };
}
protected void OnStarted() {
Started(this, EventArgs.Empty);
}
protected void OnStopped() {
Stopped(this, EventArgs.Empty);
}
protected void OnReset() {
Reset(this, EventArgs.Empty);
}
protected void OnBreakPointHit(int breakPoint) {
BreakPointHit(this, new BreakPointEvent(breakPoint));
}
protected void OnError(System.Exception exception) {
Error(this, new ExceptionEvent(exception));
}
}
}