c# delegates – 2 fundamental categories

Update: java 8 lambda. [[mastering lambds]] P 5 mentions AA BB DD as use cases for Command pattern

AA — is the main topic of the book
BB — https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
DD — http://www.oracle.com/technetwork/articles/java/lambda-1984522.html and http://www.drdobbs.com/jvm/jdk-getting-a-head-start-with-lambdas/240008174

Today I finally feel ready to summarize the 2 usage categories of c# delegates. If you are new like me, it’s better to treat them as 2 unrelated constructs. Between them, the underlying technical similarities are relevant only during initial deep dive, and become less important as you see them in various patterns (or “designs”).

In java, these features are probably achieved using interface + other constructs. Dotnet supports interfaces too, but in some contexts offers more “specialized” constructs in the form of delegates. As shown below, in such a context interfaces are usable but less than delegates.

Most tutorials would start with unicast delegate, without the inv list.

Coming from a java or c++ background, you will want to find a counterpart or close equivalent to delegates. Almost hopeless for BB. For AA there are quite a few, which adds to the confusion.

AA) lambda as function AAArgument
* I believe compiler converts such a lambda into a STATIC method (there’s really no host object) then bind it to a delegate Instance
* often returns something
* Usually _stateless_, usually without captured variables.
* predominantly unicast
* Action, Func and Predicate are often used in this context, but you can also use these 3 constructs as closures, which is a 3rd category beyond AA and BB
* Domain? Linq; functor argument as per Rajesh of OC
* Before java 8, often implemented as an interface or an anonymous inner class

BB) event field Backed by a multicast delegate instance (See other posts on “newsletter”)
* Usually NON-STATIC methods, esp. in GUI context
* Usually returns void
* A callback method is usually _stateful_, because the callback method often does its job with “self-owned” i.e. this.someField objects, beyond the argument objects passed in
* event is a pseudo _f i e l d_ in a class. Static field or non-static field are both common.
* Domain? GUI + asynchronous WCF
* we must register the callback method with the event source.
** can lead to memory leak
* in java, implemented by several callback Objects supporting a common interface (cf swing)


Some of the other categories —
CC) CCClosure — stateful, seldom passed in as a func arg
DD) thread start
EE) Passing in a delegate instance as a function input is the lambda usage (AA). How about returning from a function? P83 [[c#precisely]] shows examples to return an anon delegate instance. This is an advanced and non-trivial unicast use case. The underlying anon method is usually static and stateless

In a source code with AA, we see lots of custom delegate Types created on the fly.

In a source code with BB, delegate Instances take center stage, since each instance is assigned to a … pseudo field. The delegate type is less complicated.

memory leaks in one WPF/Silverlight app

The app has multiple screens (windows). A user can open and close them throughout a login session.

The acid test – when we close a data-heavy window, actual memory usage (not the virtual) should reduce. In our case, memory stayed high. In some cases it reached 1G+ and the entire application crashed. We fixed the issue – capped at 300M.

The leaks and the fixes

* Event registration was found to be the #1 category. In window OnClose, a lot of clean-up was needed. Release references, unregister events.

* Dispose() method was added to many classes.

some random comparisons – wpf ^ swing

I'm no expert. Just some observations of a newbie

* jtable vs grid

* dependency property, attached property – fundamental in wpf. No counterpart in swing.

* events (field-like delegate fields) are used throughout wpf, not only for event-handlers on a visual component (like button's mouse-click)

* the containment hierarchy is central to wpf command routing, event routing, property inheritance, and data binding. In swing, ……

* property change listener is another area to compare

* declarative programming via xaml? Many basic functionalities of xaml can be achieved in c# code, which looks like swing code.

* routed event? How does swing handle it?
* commanding? No such feature in swing.
* in both technologies, a visual object comprises many constituents.

AttachedProperty – clarifying questions

Attached Property is a tricky construct. When confused, a beginner (like me) could ask a few key questions

Q: Which class (not “object”) defines the AProp?
Q: Which object’s (not “class”) hashtable holds the property value?

The holder object is the visual/screen object “decorated” by the property value. Just like Opacity, “Dock.Left” describes some aspect of a visual. The “provider” is a class not an object. The AProp provider class is like a category or namespace, and tells us what category this property falls into. Is it a docking property or a text formatting property?

Any AProp (or any DProp) data can be seen as a key-value pair. In the Dock example, an OKButton’s hashtable holds the value of “Left” under the key DockPanel.DockProperty. Note the property is “specified” or “defined” not by Button class but by the DockPanel class.

After the OKButton saves the “Left” value, the natural question is who reads it? Answer — The container. In this case, the user of this property happens to be an instance of the provider class — DockPanel. In some cases, the user is unrelated to the AProp provider. You can even attach a nonsensical property to a nonsensical object, so the property value is never used.

dispatcher ^ dispatcherObject in WPF — some simple tips

Probably a low-level detail we seldom need to know. Don't spend too much time here.

See P928 [[Pro WPF in c#]]

I feel DispatcherObject means “UI object under a UI dispatcher”. Every visual (including Button) derives from the type System.Windows.Threading.DispatcherObject. See http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.asp

DispatchObject as a base class also offers the popular methods
– this.CheckAccess() and

– this.VerifyAccess()

Every DispatcherObject (including myButton) has a this.Dispatcher property, whose type is  System.Windows.Threading.Dispatcher

why minimize code behind xaml

I feel this is a valid question. Many wpf designs make this a high priority. It takes extra effort. Why make the “sacrifice”?

Code behind is a melting pot paradigm. In contrast, code in VM, M and command classes are far easier to read, test and modularize. They are often much shorter. These classes often have very few members. To a certain extent, I would say the more classes you use to organize the code, the better — imagine all of these logic put into one class — the code behind:(

See also http://stackoverflow.com/questions/3878610/why-keep-code-behind-clean-and-do-everything-in-xaml

Codebehind is considered part of Xaml and in the View layer. The code logic in CB is married to the view and not Reusable.

It’s considered best practice to
– move stuff from code behind to xaml or
– move stuff from code behind to VM or other c# classes

The reverse is usually easier — quick and dirty, sometimes clever manipulations to achieve an effect. These manipulations done in CB tend to be messy and not modularized or compartmentized.

tricks – wpf/swing IV

As my friend Guillaume pointed out, a lot of GUI know-how fall into the “tricks” category. Just open any cookbook on WPF/swing. (Let's not elaborate why GUI technologies have this commonality.)

Q: How would you deal with “how-would-you” interview questions ☺

A: prioritize according to rarity. Avoid those tricks less widely needed

A: prioritize among the visual components by rarity. jtable is by far the most used jcomponent in swing. I wasted a lot of time over text-related components.

A: real time application and related tricks are priority

A: memory management is priority but there are no feature “tricks” here

A: prioritize according to layer. Some knowledge is fundamental and used in a lot of tricks. Perhaps browse some books

*dispatcher/EDT

*dependency property, attached property

*event handler

xaml resource dictionaries – a few pointers

What's the confusion with RD elements “” and WR

elements “”?

1) All these elements define an INSTANCE of the ResourceDictionary

class. If you see 5 chunks of it in a xaml, then in the VM there will

be 5 instances(?).

2) I believe most visual controls have a non-static property

Resources, of type ResourceDictionary. Therefore Each layer on the

containment hierarchy should offer a ResourceS field, often empty. You

can populate it like



See http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.resources.aspx

3) This “Resources” field often encloses a RD element, instantiating

an RD instance. Often the element simply define the

key/value pairs, without an RD layer — Confusing.

4) The resource dict instance at any Container level is available to

be shared by the children. The highest level is probably Application

level, but i usually use the Window level. That meets my basic needs

of sharing a resource.

[[wpf succinctly]] points out

You can create a resource dictionary at the Application, Window, and

UserControl levels. A custom RD allows you to import your own C#

objects to use (and share) in XAML data binding.

A common practice is to put your view model Instance in a window-level

RD. See [[wpf succinctly]]. This resource must be defined before it's

used as a data context.