Confused in Events & RelayCommand (C#) - c#

I am a beginner in Events, trying to built a MVVM......
**Question 1:
Referring to some online example of overriding a ArrayList class with events:
http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx
public delegate void ChangedEventHandler(object sender, EventArgs e);
public class ListWithChangedEvent: ArrayList
{
public event ChangedEventHandler Changed;
protected virtual void OnChanged(EventArgs e) {if (Changed != null) Changed(this, e);}
...
}
Am I correct to say that if I override any class by adding an event into it, whenever any member/method inside the overrided class was changed/called, the method OnChanged will be automatically run? (and I can see it when debugging?)
**Question 2:
Sorry quite confused with what is doing inside RelayCommand. Specifically why in the EventHandler CanExecuteChanged it Add and then Remove the method from the ConfigurationManager simultaneously?
Thanks in advance.

As for your 1st question, I think you misunderstand something; just adding a method called OnChanged does not have the effect you describe. As with any other method, it must be called by some other code to be executed. As the base class and its methods do not know anything about the derived class, they do not invoke the method/event - and not even "by convention" because it is named OnChange.
I'm not sure whether I understand your 2nd question correctly. The CanExecuteChanged event is used to notify the UI that something has changed that influences whether a command can or cannot be executed. I don't know your code or the sample you are referring to in regards to ConfigurationManager, but removing and adding an event handler is generally done in order to assert that an event handler is registered exactly once. If you register an event handler several times, it is called multiple times - a behavior one would rarely want. Therefore one removes the event handler before registering it anew.

Related

extending control - use sender or this

I am extending a control's capabilities. I want to know if there are any advantages in using a casted sender vs this keyword in an event. For example:
public class CustomTextBox : TextBox
{
public CustomTextBox()
{
Loaded += CustomTextBox_Loaded;
}
void CustomTextBox_Loaded(object sender, RoutedEventArgs e)
{
//use either
var c = (CustomTextBox)sender;
//or
var c2 = this;
//do whatever...
}
}
I believe using this might be more efficient (No casting necessary).
usually events are handled outside the class which publishes them, in the subscriber class. In such a setup, it may be desired to get the reference of publisher in subscriber & that is when type casting the sender to get the reference of publisher comes handy.
I agree, in my opinion, if you can get the reference of publisher without type casting thats better, you should use this.
But since you are extending a control, please check if its really necessary to use event of the base class. An event is for the outside world, and not for child classes.
If the event pattern has been implemented correctly in the base control class, I would expect a virtual method responsible for raising which you can override while extending the control, like this -
class CustomTextBox : TextBox
{
protected override void OnClick(EventArgs e)
{
//place your code here if you want to do the processing before the contol raises the event. Before call to base.OnClick(e);
base.OnClick(e); // call to base funciton fires event
//place your code here if you want to do the processing after the contol raises the event. After call to base.OnClick(e);
}
}
Hope it helps.
I doubt you would find any measurable performance difference either way, especially for an event like Loaded that is only going to be raised once during the lifetime of the control.
That said, it seems to me you should go ahead and use this, just because it's more convenient and expressive. If your method is already in the code of the class of the sender, why not? What possible gain could there be in code comprehension, ease of authoring, maintainability, or any other common goal in programming to using the sender parameter instead of just using this?

C# - issue with custom raising events

I have my class where I define my event:
public class EventRaiserUtility
{
public event EventHandler updateList;
public void updateListEvent()
{
if (updateList != null)
{
updateList(this, EventArgs.Empty);
}
}
public static EventRaiserUtility raiser = new EventRaiserUtility();
}
and this is where I raise my event:
EventRaiserUtility.raiser.updateListEvent();
and finally this is where I'm trying to create the listener:
...
EventRaiserUtility.raiser.updateList += new EventHandler(raiser_updateList);
//placed in the init method of another class
...
private void raiser_updateList(object sender, EventArgs e)
{
connType = MainWindowViewModel.getTTC();
}
Simply: this event has to notify when a list is updated and then update another list, with getTTC() with raiser_updateList.
But raiser_updateList is never called. Why? All my 3 snippets of code are in 3 different classes (same project), but this isn't a problem... right?
You're creating a new EventRaiserUtility just before you call updateListEvent (which should have a capital U to follow .NET conventions, by the way; ditto updateList => UpdateList) - but you're creating a separate EventRaiserUtility in order to subscribe to the event. They're different objects, so have different event subscribers. If you always create a new object before raising the event, there could never be any subscribers.
You should have a single EventRaiserUtility stored in an instance variable in the containing class - you'd create that on construction, then subscribe to the event in one place an raise it in another... but because they'd be talking about the same EventRaiserUtility object, you wouldn't lose the subscription.
(It's not clear that this utility class actually has much value, to be honest - why aren't you just declaring the event in your class directly? And why declare your own delegate when EventHandler has exactly the same signature?)
As far as I can see - you are subscribing to the event of one instance of EventRaiserUtility, but raising event from another instance which has no subscribers
you need one object to really own the event. Maybe that is the EventRaiserUtility, but you'd still need to make the same instance available in both classes. Without knowing the relationship between those classes

Why public event cannot be invoked outside directly?

Consider we have a class with event declared:
public class FooBar
{
public event EventHandler FooBarEvent;
}
Despite of "publicness" of the event, we cannot call FooBarEvent.Invoke from outside.
This is overcame by modyfing a class with the following approach:
public class FooBar
{
public event EventHandler FooBarEvent;
public void RaiseFooBarEvent(object sender, EventArgs eventArguments)
{
FooBarEvent.Invoke(sender, eventArguments);
}
}
Why accessing public events outside is limited by adding and removing listeners only?
Defining a public event merely gives consumers the ability to subscribe and unsubscribe from it. The ability to raise the event is limited to the type hierarchy which declares the event.
Allowing all subscribers to also be able to raise the event would be a bit chaotic. Imagine for example I had a TextBox class which had a Focused event. If any old consumer could raise the event then the Focused event could easily fire when the TextBox class wasn't actually focused. This would make it nearly impossible to maintain any type of invariant during an event.
Personally I think this is done to properly convey the design principles behind the whole events architecture.
The purpose of an event is to notify a listener of said event occurring in a given object.
What's the point of raising events of classes that don't belong to you?
That's what events are for. If you want to invoke it publicly you probably need delegates not events
Events gives encapsulation,
It prevents other classes from assigning anything to it
It prevents passing it as a parameter to methods
It prevents assigning it to any variable
It prevents calling it from another classes (not even derived classes have access to it)
etc
public accessibility tells that it can be subscribed from anywhere, not invoked from anywhere.
the answer to your question is
An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object.
Invoking the event from outside doesn't makes sense therefore it is not allowed.
I think you should change your perspective on how events work. Other classes shouldn't "own" the event and trigger it. Classes which "listen" to the event by "subscribing" to it and do a certain action when this event occurs.
That's the way the language is defined - an event can only be fired by the owning class. If you must fire it from a different class, have the owning class define a public method that will fire the event:
public FireFooBarEvent (object sender, EventArgs args)
{
if(FooBarEvent != null)
FooBarEvent(sender, args);
}
And call this method from any class.

Is it really an error to override events in C#?

I read in this question: Overriding Events in VB
It is even an error to override events in C#. The C# Programming Guide says:
Do not declare virtual events in a base class and override them in a derived class. The C# compiler does not handle these correctly in Microsoft Visual Studio 2008 and it is unpredictable whether a subscriber to the derived event will actually be subscribing to the base class event.
I wonder why a framework class breaks this rule, or even why the compiler allows it.
I can't understand why it's a mistake to override events. Sure an inheriting class can always monitor the base class event and take it's own actions afterwards, but what if it wants to ensure that it is the first event observer to see the event? What it it wants to decide to swallow the event under certain conditions? What's wrong with doing something like this:
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
VerifyActiveCountMatches();
base.OnCollectionChanged(e);
InvokePropertyChanged("Count");
}
It's not an error to do so - but it may well be a bad design decision. There's a big difference; the compiler won't let you get away with an error, but it rarely criticizes your design.
The code you've shown for OnCollectionChanged does not override an event - it overrides the method which raises the event. That's an entirely different matter. An event is something like:
// "Field-like" event - the compiler implements the add/remove and
// creates a backing field.
public event EventHandler Click;
or
// Manually-implemented event; you write the add/remove yourself, and
// create a separate backing variable if necessary.
public event EventHandler Click
{
add { ... }
remove { ... }
}
These are the pieces of code which handle the subscription and unsubscription - and it's these that the advice is saying you shouldn't override. You'd rarely want to, and as the quoted text says, there are plenty of situations where it wouldn't do what you wanted it to anyway.
That is not overriding the event, you are overriding the event invoker there (possibly a handler, but that pattern usually denotes a protected member that is used to invoke the event handler).
Overriding an event would look something like:
public override event EventHandler CollectionChanged;
I'm quoting this blog:
"Using a virtual field-like event in the parent class and not changing any of its behavior in the overriding derived class is not necessary. You can simply omit the override in the derived class to get the desired behavior."
If you aren't changing behavior then why make it virtual? As pointed out, this is different than overriding the method that raises the event.

Why to use events somewhere where method is enough?

I read some events tutorial and just do not get what is the benefit in simple code like this..method should be used the same way:
class Bulb
{ public delegate void handler();
public event handler Glowing;
...
Glowing+=SomeMethod;
private void TurnOn
{
Glowing();
}
private void SomeMethod
{
}
}
Simply Events allow others using your code to perform some custom Implementation they want when that Event occurs (when Bulb is Glowing).
Simply calling your method won't tell anybody that something has happened.
Events are very basic Element of any Event Driven Programming
If your program doesn't need to tell about an event you don't need to implement such Functionality. However having such functionality has benefits.
For Example when using a List Class you dont know when an Item got added to it (if at some point some other code does that) but in a ObservableCollection you get notifications when Items are Added or Removed.
An event is a message sent by an object to signal the occurrence of an action. The action could be caused by user interaction, such as a mouse click, or it could be triggered by some other program logic.
The idea is that a different class which can hold Three different Bulbs can get notified by the event (if it implements a handler) that the light has been turned on and is Glowing.
So the benefit does not reside in the simply class but in what ever classes/objects are going to be holding/using instances of the Bulb class.
Hope that made some sense :)
Events over methods become handy when you have a class dependency that needs to know or be notified about a stateful change:
public class Lamp
{
Bulb inThelamp = new Bulb();
inTheLamp.Glowing += myLampMethod;
// If these arguments have been defined for this event that is
public void myLampMethod(object sender, EventArgs e)
{
// Code to react to the light suddenly being on
}
}
This allows the Lamp class to recognize that something has turned the bulb on. In many cases it will be through some action in the Lamp (click, pushknob, etc). But in some cases it could be an external class that calls a public Bulb property directly without using the Lamp itself (such is if(PowerCompany.BillsPaid) Lamp.BulbInTheLamp.TurnedOn();). This is all assuming that the modifiers are set to allow this kind of access.
The point is that it allows notification of an occurrence rather than requiring that a particular method be called manually each time you want an action to occur.

Categories