Why is generic EventHandler<TArgs> so under-used? - c#

.NET 2.0 added the EventHandler<TArgs> generic delegate type to simplify the process of writing custom events; instead of having to define an EventArgs class and its corresponding delegate (e.g. MyEventArgs and MyEventHandler), you need only write the args class.
Bearing that in mind, why does this delegate type appear almost nowhere in the .NET Framework? I know that most of the core APIs were developed before generics were introduced, but even in new parts of the framework like WPF, they have opted for explicitly defining delegate types; e.g. RoutedEventHandler instead of EventHandler<RoutedEventArgs>.
Is there something inherently wrong with the generic event handler delegate? I often make use of it and I worry that my code appears very out of place when compared to built-in classes.

Just an accident of history. If we had generics in .NET 1 most of the other delegates wouldn't exist.

I don't think there's anything wrong with it. It is used in some places of the framework... in the GeoCoordinateWatcher.Position event, just as a random example.
It's a little clumsier to see in code than a specific type name like RoutedEventHandler - and as you're going to use RoutedEventHandler a lot in WPF/Silverlight, maybe that's why MS decided to give it its own type.

It could also be that when you're writing framework level code you tend to be more explicit. When you write toolkit and application level code not so.

The following is just my personal oppinion, but it seems (oviously) reasonable for me;
If we take a close look of how you work using .net and v studio, it appears that generic type notation seems to leak some "beauty".
List<string> lst = new List<string>();
lst.Add("hello world");
While the code above is pretty simple, straight forward and well supported by intelli sense the EventHandler "look and feel" doesnt appear that clear. The default intelli support will suggest just the EventHandler, not its generic. Further the notation just looks awfull:
private event EventHandler<MyClass> SomeEvent;
private event EventHandler<AnotehrClass> OtherEvent;
privete event EventHandler<MoreClass> MoreEvents;
While overviewing the code you will read "EventHandler" every time and your mind might connect those delegates, beacuse you are used to identify the relationship of types by their names.
On the other side there might also be a less isoterical and more technical/logical explanation:
First of all you always get a sender object in the handling method. While this seems usefull at first glance - it is barley ever used.
Further your arguments have to derive from EventArgs which might be annoying or sometimes even just immposible due to the usage of existing components.
Other than the the typical generics (e.g. IList/List) you leak the possibility to use a more abstract type (like an interface) or just a simple type (like a double).
Last but no least there are those notation rules/suggestions introduced by microsoft - for your example about the routed event the rule might say that its type is "marked" as beeing routed by having its name stared with the word "Routed". While the naming for the event by itself says the the name startes with a "Preview". As i mentioned: this is just my opinion so dont blame me ;)

Related

Is it bad practice to use Action and Func all the time instead of making corresponding delegates?

A lot of time when creating simple events in my program that other classes can subscribe to instead of making a delegate and creating an event from the delegate I just create the event with either Action or Func to avoid having to create the delegate.
Is there any downsides to doing this?
Not really, the only downside I can think of is that if you have a logical intention (beyond the parameters and return values expected) that you want the user to satisfy that may get lost using the generic delegates.
For example:
public delegate void ClearAllValuesDelegate(MyClass X);
// ...
ClearAllValuesDelegate myDelegate;
vs:
Action<MyClass> myDelegate;
In the former, it's clear the intention is that the action should clear all the values in the reference (though there's no way to enforce this of course). Whereas Action<> just tells you what it takes and not much else. Like I said, this is just a logical difference.
But really there's no big downside that I'm aware of. Most of the time when we use Func<> and Action<> we are simply asking the caller to give us a target that satisfies the inputs/outputs only.
The main difference to me is the difference between:
And:
Obviously, there is at least some value in having the parameter named.
imho it's a matter of preference, to the CLR it's the same thing

use Func<> (or Action<>) or create own delegate?

Which one is better in, say, parameter type in a method (not related to LINQ).
Apparently Func is better since it's simpler, more descriptive, and if everyone is using this everything will become compatible (good).
However I notice Microsoft uses its own delegate at some libraries, for example event handlers. So, what are the advantages and drawbacks of either of them? when should I use it?
Edits:
Apparently Func<> was only available in 3.5, so this can possible be the main reason that I saw non-Func delegates. Any other reason to not use Func? (example: this is from .NET4)
The same question also applies for Action<>
Func<> is useful when it's very clear what they're used for, and the number of inputs is small.
When the number of inputs is larger, or there could be some ambiguity over the intent - then using a delegate with named arguments makes things clearer.
They are for all purposes the same, except when the method has an Expression parameter. Those need to be defined as a 'lambda' and not delegate. This would be very problematic when dealing with IQueryable and getting the IEnumerable invoked/resolved instead (eg LINQ2SQL).
Func<> and Action<> are preferable if they are actually appropriate in your case.
Runtime creates instances of every type used in your program, and if you use Func once it means that the instance of type was created. In case of custom delegate things go in different way and new types will be created even though they are essentially similar to existing.
However sometimes custom delegates make code clearer.
However I notice Microsoft uses its own delegate at some libraries, for example event handlers. So, what are the advantages and drawbacks of either of them? when should I use it?
Some of this is historic: APIs defined before C#3/.NET3 when Action<> and Func<> were added. For events EventHandler<T> is a better choice for events because it enforces the right convention.
You can always create a class which holds the n number of input as class properties and pass the object of the class a single input in the func<> delegate

What's the deal with delegates?

I understand delegates encapsulate method calls. However I'm having a hard time understanding their need. Why use delegates at all, what situations are they designed for?
A delegate is basically a method pointer. A delegate let us create a reference variable, but instead of referring to an instance of a class, it refers to a method inside the class. It refers any method that has a return type and has same parameters as specified by that delegate. It's a very very useful aspect of event. For thorough reading I would suggest you to read the topic in Head First C# (by Andrew Stellman and Jennifer Greene). It beautifully explains the delegate topic as well as most concepts in .NET.
Well, some common uses:
Event handlers (very common in UI code - "When the button is clicked, I want this code to execute")
Callbacks from asynchronous calls
Providing a thread (or the threadpool) with a new task to execute
Specifying LINQ projections/conditions etc
Don't think of them as encapsulating method calls. Think of them as encapsulating some arbitrary bit of behaviour/logic with a particular signature. The "method" part is somewhat irrelevant.
Another way of thinking of a delegate type is as a single-method interface. A good example of this is the IComparer<T> interface and its dual, the Comparison<T> delegate type. They represent the same basic idea; sometimes it's easier to express this as a delegate, and other times an interface makes life easier. (You can easily write code to convert between the two, of course.)
They are designed, very broadly speaking, for when you have code that you know will need to call other code - but you do not know at compile-time what that other code might be.
As an example, think of the Windows Forms Button.Click event, which uses a delegate. The Windows Forms programmers know that you will want something to happen when that button is pressed, but they have no way of knowing exactly what you will want done... it could be anything!
So you create a method and assign it to a delegate and set it to that event, and there you are. That's the basic reasoning for delegates, though there are lots of other good uses for them that are related.
Delegates are often used for Events. According to MSDN, delegates in .NET are designed for the following:
An eventing design pattern is used.
It is desirable to encapsulate a static method.
The caller has no need access other properties, methods, or interfaces on
the object implementing the method.
Easy composition is desired.
A class may need more than one implementation of the methodimplementation of the method
Another well put explanation from MSDN,
One good example of using a
single-method interface instead of a
delegate is IComparable or
IComparable. IComparable declares the
CompareTo method, which returns an
integer specifying a less than, equal
to, or greater than relationship
between two objects of the same type.
IComparable can be used as the basis
of a sort algorithm, and while using a
delegate comparison method as the
basis of a sort algorithm would be
valid, it is not ideal. Because the
ability to compare belongs to the
class, and the comparison algorithm
doesn’t change at run-time, a
single-method interface is ideal.single-method interface is ideal.
Since .NET 2.0 it has also been used for anonymous functions.
Wikipedia has a nice explanation about the Delegation pattern,
In software engineering, the delegation pattern is a design pattern in object-oriented programming where an object, instead of performing one of its stated tasks, delegates that task to an associated helper object. It passes the buck, so to speak (technically, an Inversion of Responsibility). The helper object is called the delegate. The delegation pattern is one of the fundamental abstraction patterns that underlie other software patterns such as composition (also referred to as aggregation), mixins and aspects.
Oversimplified: I'd say that a delegate is a placeholder for a function until that time when something assigns a real function to the delegate. Calling un-assigned delegates throws an exception.
Confusion occurs because there is often little difference made between the definition, declaration, instantiation and the invocation of delegates.
Definition:
Put this in a namespace as you would any class-definition.
public delegate bool DoSomething(string withThis);
This is comparable to a class-definition in that you can now declare variables of this delegate.
Declaration:
Put this is one of function routines like you would declare any variable.
DoSomething doSth;
Instantiation and assignment:
Usually you'll do this together with the declaration.
doSth = new DoSomething(MyDoSomethingFunc);
The "new DoSomething(..)" is the instantiation. The doSth = ... is the assignment.
Note that you must have already defined a function called "MyDoSomething" that takes a string and returns a bool.
Then you can invoke the function.
Invocation:
bool result = doSth(myStringValue);
Events:
You can see where events come in:
Since a member of a class is usually a declaration based upon a definition.
Like
class MyClass {
private int MyMember;
}
An event is a declaration based upon a delegate:
public delegate bool DoSomething(string withWhat);
class MyClass {
private event DoSomething MyEvent;
}
The difference with the previous example is that events are "special":
You can call un-assigned events without throwing an exception.
You can assign multiple functions to an event. They will then all get called sequentially. If one of those calls throws an exception, the rest doesn't get to play.
They're really syntactic sugar for arrays of delegates.
The point is of course that something/someone else will do the assigning for you.
Delegates allow you to pass a reference to a method. A common example is to pass a compare method to a sort function.
If you need to decide at runtime, which method to call, then you use a delegate. The delegate will then respond to some action/event at runtime, and call the the appropriate method. It's like sending a "delegate" to a wedding you don't want to attend yourself :-)
The C people will recognize this as a function pointer, but don't get caught up in the terminology here. All the delegate does (and it is actually a type), is provide the signature of the method that will later be called to implement the appropriate logic.
The "Illustrated C#" book by Dan Solis provides the easiest entry point for learning this concept that I have come across:
http://www.amazon.com/Illustrated-2008-Windows-Net-Daniel-Solis/dp/1590599543
A delegate is typically a combination of an object reference and a pointer to one of the object's class methods (delegates may be created for static methods, in which case there is no object reference). Delegates may be invoked without regard for the type of the included object, since the included method pointer is guaranteed to be valid for the included object.
To understand some of the usefulness behind delegates, think back to the language C, and the printf "family" of functions in C. Suppose one wanted to have a general-purpose version of "printf" which could not only be used as printf, fprintf, sprintf, etc. but could send its output to a serial port, a text box, a TCP port, a cookie-frosting machine, or whatever, without having to preallocate a buffer. Clearly such a function would need to accept a function pointer for the character-output routine, but that by itself would generally be insufficient.
A typical implementation (unfortunately not standardized) will have a general-purpose gp_printf routine which accepts (in addition to the format string and output parameters) a void pointer, and a pointer to a function which accepts a character and a void pointer. The gp_printf routine will not use the passed-in void pointer for any purpose itself, but will pass it to the character-output function. That function may then cast the pointer to a FILE* (if gp_printf is being called by fprintf), or a char** (if it's being called by sprintf), or a SERIAL_PORT* (if it's being called by serial_printf), or whatever.
Note that because any type of information could be passed via the void*, there would be no limit as to what gp_printf could do. There would be a danger, however: if the information passed in the void* isn't what the function is expecting, Undefined Behavior (i.e. potentially very bad things) would likely result. It would be the responsibility of the caller to ensure that the function pointer and void* are properly paired; nothing in the system would protect against incorrect usage.
In .net, a delegate would provide the combined functionality of the function pointer and void* above, with the added bonus that the delegate's constructor would ensure that the data was of the proper type for the function. A handy feature.

very simple delegate musing

Sometimes the simplest questions make me love C/C++ and C# more and more.
Today sitting on the bus musing aout delegates I remembered
reading somwhere you don't need to use the new keyword when instaniating
a new delegate.
For example:
public static void SomeMethod(string message)
{
...
}
...
public delegate void TestDelgate(string message); //Define a delegate
...........
//create a new instance ..METHOD 1
TestDelgate t = new TestDelgate(SomeMethod);
//OR another way to create a new instance ..METHOD 2
TestDelgate t = SomeMethod; //create a new instance ..METHOD 2
So todays questions are
What happens under the hood in method 2. Does the compiler expand method 2 into method 1, hence writing TestDelgate t = SomeMethod; is just a shortcut for
TestDelgate t = new TestDelgate(SomeMethod);, or is there another reason for the exsitence of method 2
Do you guys think method 1 or method 2 is better for readability (this is a subjective question, but I'd just like to get a unscientific feel of general opinion of stackoverflow :-))
Yes, method 2 is just shorthand for method 1 - at least in the case of using a method group. You can also use:
TestDelegate t = new TestDelegate(someExistingDelegate);
which allows for variance (not just the generic variance from C# 4) and creates a separate delegate... but that's rarely useful.
Personally I go with option 2... method group conversions are very handy like that. In particular it makes event wiring simpler:
button.Click += LoadDocument;
instead of
button.Click += new EventHander(LoadDocument);
The latter just has extra fluff - the former has better information density. It's also important when you're passing the delegate as a method argument. For example, compare:
observable.Subscribe(new Action<string>(Console.WriteLine));
with
observable.Subscribe(Console.WriteLine);
Unless there's any ambiguity in terms of which delegate type you actually want to convert the method group to, I just use the implicit conversion.
Under-the-hood, your 2 methods are exactly the same. It is just the compiler being smart about what you want to do. This little feature is called delegate inference and was added in C#2.0.
I think you should use #2, and take advantage of delegate inference. They compile to the same IL, and option #2 is shorter and more concise. It is easier to read and understand the meaning of the code, because there is less noise.
This syntax is also supported for events.
It is sugar. The kind of sugar that really comes in handy when you have to write this:
someObj.Test -= new TestDelegate(SomeMethod);
What? You have to use the new keyword to remove an event handler. Yes, you do. The VB.NET team really pained about this, they decided for a completely different syntax:
RemoveHandler someObj.Test, AddressOf SomeMethod
Even the above C# statement is sugar, the real code looks like this:
someObj.Test.remove(new TestDelegate(this, SomeMethod));
Where "remove" is the accessor function for an event. And "this" is required to initialize the Delegate.Target property. Now it is obvious that it is actually a method call and using the new keyword suddenly makes sense again. Hiding "this" has some disadvantages too, it isn't obvious anymore that an event subscription will prevent an object from getting garbage collected.
Yes they are compiled into the same thing.
I prefer #2. Just because it is shorter and not so clumsy. You already know that it is a TestDelegate due to defining that before. So why write it again?
It's just syntatic sugar for the explicit delegate creation. This was introduced in C# 2.0. You may have noticed that Visual Studio 2008 still generates the old-style (method 1) syntax if you ask it to create an event handler; I always replace it manually by the new syntax.
I normally prefer the shorter form in method 2. I used method 1 only once: with a delegate that was to be invoked from native code, and therefore could not be garbage-collected. I wanted to be very explicit about creating and assigning it.
Under the hood both statements create delegate object and pass to parameters to ctor: address of method and reference to this. second is just syntax sugar.
One advantage of the 'new' syntax is that it informed the programmer that a new object was being allocated; if it would be desirable to avoid repeatedly creating new identical delegates, one could pull the delegate out to a field. I know that in fact one is allowed to use one delegate to subscribe and another to unsubscribe, but to me that feels wrong. Storing to a field the delegate used to subscribe, and then unsubscribing using that same delegate feels cleaner. Cleaner still, IMHO, would have been if the act of subscribing would have returned a MethodInvoker which, when called, would unsubscribe (in which case an "event" would simply be a function that accepted an EventHandler and returned a MethodInvoker), but that's not how .net events work.

What is the practical use of "dynamic" variable in C# 4.0?

What is their use if when you call the method, it might not exist?
Does that mean that you would be able to dynamically create a method on a dynamic object?
What are the practical use of this?
You won't really be able to dynamically create the method - but you can get an implementation of IDynamicMetaObject (often by extending DynamicObject) to respond as if the method existed.
Uses:
Programming against COM objects with a weak API (e.g. office)
Calling into dynamic languages such as Ruby/Python
Potentially making "explorable" objects - imagine an XPath-like query but via a method/property calls e.g. document.RootElement.Person[5].Name["Attribute"]
No doubt many more we have yet to think of :)
First of all, you can't use it now. It's part of C#4, which will be released sometime in the future.
Basically, it's for an object, whose properties won't be known until runtime. Perhaps it comes from a COM object. Perhaps it's a "define on the fly object" as you describe (although I don't think there's a facility to create those yet or planned).
It's rather like a System.Object, except that you are allowed to call methods that the compiler doesn't know about, and that the runtime figures out how to call.
The two biggies I can think of are duck typing and the ability to use C# as a scripting language in applications, similar to javascript and Python. That last one makes me tear up a little.
Think of it as a simplified form of Reflection. Instead of this:
object value = GetSomeObject();
Method method = value.GetType().GetMethod("DoSomething");
method.Invoke(value, new object[] { 1, 2, 3 });
You get this:
IDynamicObject value = GetSomeObject();
value.DoSomething(1, 2, 3);
I see several dynamic ORM frameworks being written. Or heck write one yourself.
I agree with Jon Skeet, you might see some interesting ways of exploring objects.
Maybe with selectors like jQuery.
Calling COM and calling Dynamic Languages.
I'm looking forward to seeing if there is a way to do a Ruby-like missing_method.

Categories

Resources