GetNoticed IT#3: S-O-L-I-Dependency Inversion Principle

Hi there!
One day I want to be professional dev. In order to do that I need not only to write something that works but also is written in proper manner. What that means? Every time that matter is discussed conclusion is always the same: properly written code is simple, testable, easily maintainable and expandable. Some time ago ca. 2000 a set of rules was established to achieved that. These rules were defined by Robert Martin and Michael Feathers and are called SOLID.

S – Single Responsiblity Principle
O – Open/Closed Principle
L – Liskov Substitution Principle
I – Interface Segregation Principle
D – Dependency Inversion Principle

Some say that the last one is the most important (for instance, founder of Get Noticed contest here: https://youtu.be/SnsIw3cZR5k?t=4m5s) as it allows developers to write loosely coupled (internal dependencies-wise) applications. For that very same reason I will start this short series of posts about SOLID principles.

High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions.

It would be best to explain that using an example. Assume that we’re building an application to handle purchase orders. Let’s consider this small piece of code:

In our application we have two classes: Item which describes items we have to sell; and OrderHandler which handles an actual order by adding tax and shipping cost. In this case class OrderHandler depends on class Item. That is DIP violation. To fix it we need to abstract Item class.

In the code above there is ICanBeSold interface defined which has only one get-only property. That’s enough for our OrderHandler as it has only one method that returns total cost of ordering an item. That creates loose coupling between items and item orders. Changes in Item class would not inflict errors in OrderHandler (of course as long as it implements ICanBeSold interface). Another benefit of that is the fact that you can create multiple classes which can be used in OrderHandler.

Dependency Injection
Neat and nimble way to follow the DIP rule is dependency injection. This pattern is about designing your classes in a way that they use abstractions instead of concrete classes and whenever you need a concrete object to be used you hand the object to the class through class constructor, a method’s parameter or through property.

Injection through constructor
Let’s rebuild our application so different rules of discounting can be applied. For instance, we need to allow free shipping sale and abroad shipping. In order to achieve that we’ll create new class called PriceCalculator.

Take a look at the code above. Now OrderHandler class can be used to sell anything that implements ICanBeSold interface by rules set by anything that implements IPricingRules interface. What is that going to be is now passed to OrderHandler in its constructor.

So, actually there are two dependencies injected through the constructor.

Dependency injection through a method
If our OrderHandler is going to be used to do something more than perform one-time action it might be better to consider injecting a dependency through its method. It is very similar to what I have described above. The difference is that the dependency is given as a parameter to one of methods available in high level class. Let’s rebuild our OrderHandler again:

In the example above IPricingRules is injected to ProceedeSale method. That allows us to use different rules every time we want to do the sale. The example above has been simplified slightly by replacing item injection by simply giving its value in OrderHandler constructor. Now, take a look a the code below:

We’re proceeding with the sale twice but each proceeding has its own rules defined by IPricingRules implementation.

Injecting through property
Another way to inject a dependency is through property. In this case we simply create a IPricingRules property with both getter and setter. Now, every time we want to change pricing rules we simply set value of this property. Our rebuilt OrderHandler would look like that:

And here’s its usage:

Other means
However simple Dependency Injection is and, I presume, most common way to follow the DIP it isn’t the only way. For example, a delegate can also be considered as a way to achieve dependency inversion since a delegate is also form of abstraction. Let’s again rebuilt our OrderHandler class and equip it with a delegate to use for custom sales:

And its usage:

In the above we’re using Lambda expression as a delegate but here we could set whatever method we want including one from different class.
So, these are basics of Dependency Inversion Principle and Dependency Injection. Here are some recommendations where to look for further information about the topic:
http://plukasiewicz.net/Artykuly/DIP_IoC_DI
https://www.codeproject.com/Articles/159800/Inversion-of-Control-Practical-usage-of-Interface

In my next posts I will continue about SOLID principles and plausibly at some point I will write a post also about dependency injection containers.
So, thanks for reading today. In my case SOLID principles redefines how I should write code. This means that I need to restart my project again. But, as I see it, it is better  to write good code and maybe finish the project with delay or in impoverished version than to write something that works but is crap.
Good luck!

GetNoticed DEV#1: Updates in Guillotine implementation

Greetings!
It’s Sunday evening so it’s time to share updates on what has recently happened in my project.
I have to admit that progress isn’t as significant as I wished. This post is not to make excuses but I have to say a word or two to whitewash myself a bit. I started new job somewhere in the middle of February. The office is around 60 km from Dublin so I have to commute every day. To make long story short: I wake up at 4.30 am and I back home around 9 pm. That’s a long day…
Now, let’s get back to business. I want to follow the Guillotine algorithm in my project. Some may say that it’s not the best I could do. I agree, but for the time being that’s my decision. Who knows, maybe if I have some time to spare I will go for something better. We’ll see.

New things implemented from last week:
1) ArrangerResults class introduced. That allows items to be distributed into multiple sheets in case if one is not enough;
2) Calculate method in Arranger class can now check against an item being to big for declared sheet and exclude it from calculation
3) Item sorting is now achieved with classes that implment ICompare interface, which is instantiated by Arranger class
4) Checking if an item can fit into container and sectioning of remaining part of container after placing an item into it are now moved to separate methods in Arragner class (respectively method CheckIfFits and DoSection)
5) ArrangerResultsPNG class introduced which allows to create PNG file for arrangement

All the code I have written so far still needs some serious tweaks and refinements. However I am hoping to be finished with ArrangerLibrary by the end of this month. I’m sure that some updates will be required after this deadline has passed. But my plan for the application is that it’s going to be more expanded: more or less it will be possible to manage sheet cutting projects, store them and edit. This is still kinda blurry vision.

So, that’s it for today. Thanks for your attention. The code can be viewed on GitHub (https://github.com/mickaj/SheetMetalArranger). I encourage also to view other repos in my GitHub account. I would much appreciate your comments, suggestions and criticism.

Thanks and good luck!

GetNoticed IT#02: User controls in WPF

Hello!
I’m continuing learning WPF. Recently, I’ve put my focus on user controls. As I did not spend too much time mastering WinForms I didn’t do anything in this matter so far.
Default controls library offers basic set of controls you can use to build a WPF user interface. It’s easy to find a case where the same set of controls will be used frequently in your UI. First thing that comes to my mind: a tabbed interface which display some data. To make it efficient it would be reasonable to create a pattern of how those basic controls will be used in our data tab, so once user open new tab it will contain this pattern. And a user control can be understood as such.
In this presentation I will prepare an application that display a person’s details. It will consist of list of users, buttons to show details of existing person and to add new person and a tabbed panel where the application will show details of selected (or new person).

Model
The model will consist of two class: both public; one is Person class which describes one particular person some basic details, the second one ListData contains a list of all persons and some properties used to bind them with the UI. ListData can be more or less considered in this case as a view model.

PersonControl
To start building your customised control you simply need to add new item to the project and select WPF user control – that’s easy to find, no need to explain.
And here’s XAML and code-behind for the control:

The control consists of text blocks which display properties of person bound to the control. In the code-behind you can see a dependency property declared. It is of type Person (more on dependency properties here). That allows us to bind an object of this class directly to the control. What also needs to be mentioned is that the control is given name x:Name=”this”. That in turn is required to internally (in boundaries of the control itself) bind a dependency property to a certain text block in XAML <TextBlock Text=”{Binding ElementName=this, Path=ThisPerson.Balance}”/> .

As mentioned earlier class ListData would be our view model.  It implements INotifyPropertyChanged interface and shares two properties: PersonIndex and SelectedPerson. The first one is bound to SelectedIndex property of a combo box with list of all available persons and the second one is bound to our custom control.

What’s interesting is that setter for PersonIndex also changes SelectedPerson property. That works in that way that switching an item in combo box (which is bound two-way with PersonIndex) will also inflict a change in SelectedPerson.
That’s pretty simple way to build controls specifically for displaying data from custom objects. I would much appreciate if anyone smarter than me is reading that and thinks that it is not a good practice (as it is actually coupled with the model but I think it could be easily improved by introducing some abstractions).
Source code available on GitHub here: https://github.com/mickaj/PersonsUCDemo

So, that’s it for today. My plans for the weekend is to improve a bit the Guillotine algorithm I wrote implementation last week.
And here’s a goodbye riddle: in the demo you can find three persons defined. The last one is Pierre Aronnax. Who is he?

Cheers, Michal

GetNoticed DEV#0.5: Bin packing problem and Guillotine algorithm

Shalom!
First weekend of working on my application is almost gone. So the time is high to write a short report.
General thought: I am LOUSY mathematician. Not a mathematician at all!
During my student days I had never been good at it. Add the time that passed since then and you have the outcome.
But let me cut to the chase. Here’s short explanation for those of you who haven’t had a chance to read what my application is going to be. My plan is to write a program that will help engineers to optimise utilisation of sheets used for cutting flat items from steel plates. It is common activity in fabrication companies and multitude of software is now available on the market. So it’s not going to be any innovation or breakthrough.
Packing as many items as possible in given space is called bin packing problem. And there is multitude of its varieties (1D, 2D, 3D) and algorthims to solve it (shelf, guillotine, max-rectangles).
Currently, I am convinced to use guillotine algorithm. It is not the one that gets most optimal results but its implementation is quite simple and achieved results (despite that not the efficient) can be described as acceptable. So, that’s the current choice but I am not saying that it’s final.

Guillotine algorithm
Entry point for this algorithm are set of rectangles to be packed (height and width) and size of available sheet (again height and width). Rectangles are stored in a list. They will be attempted to be placed into available containers. Available spaces are similarly stored in a list. Each container is described by its height, width and bottom-left coordinates (X and Y). Initial list of containers contains only one item based on available sheet – the container has width and height derived form available sheet and bottom-left coordinates equal to 0,0.
First item from rectangle list will be placed in that only one container. After that is done the remaining space must be divided into two containers as shown in the picture below.
Decision how to split the remaining space can be based on various factors: arbitrary decision that we’re going to cut vertically or horizontally; by shorter cut-line; which cut generates a rectangle of bigger area; which cut generates a rectangle which is closest to square or which cut generates a rectangle which is most suitable for next item to be placed. It practical application it would be best to consider all options and take best results.

Next step is to place another rectangle from the list. We check which of available container can accommodate the item and which does that most effectively area-wise. And that continues until all rectangles are allocated.
To distinguish which rectangle is allocated and which container is taken I used separate lists. At the very end of each iteration I simply move the rectangle that has just been placed into a container to that second list and the same thing happens to the container – it is moved to second list.
There are also different strategies how to set the order of rectangles to be allocated. They can be sorted by area, by height or width, or by longer edge. Similarly to decision how to cut remaining space after placing a rectangle this strategy also generates different results. We choose the most optimal.
So, that’s basically it. If you wish you can check my first implementation on GitHub. But I have to warn you: the code is dirty as hell. But for the time being that’s just playing around. It will get cleaner and nicer 🙂

That’s it for today!
Regards, Michal.

GetNoticed IT#01: LQA tester episode

Hello!

Despite the fact that ever since I finished high school I’ve been working in mechanical design (and fabrication as well for a period of time) I had a chance to taste the IT business. Sometime between November last year and February this year I worked for a game testing company. I was employed as a LQA Tester which stands for Localisation Quality Assurance tester. My role was to look for all localisation bugs.
The work itself was quite enjoyable even that I’m not a die-hard gamer (FM doesn’t count). So here are my reflections from that time.
Generally, it’s not a job a professional adult could do for a longer period. At least at the position I was employed on. The reason is simple: wage. I was employed on a project basis meaning that  I worked only when there was a project for me. I was able to step into this job because I had saved a bit of funds in my pre-LQA job. But if I had to pay full bills, eat and commute to the office without that backup money it would not have been possible. So in my situation it was like having a break from serious job.
What I enjoyed the most was that geeky-fell in the office. The crew members were mostly youngsters with real passion towards games and they were a bit odd in comparison to the rest of society. At least I had that impression. Thanks to that it you couldn’t feel that you’re working in a big international corporation. Tell me which major company would allow their employees to come to work with vividly coloured hair, ear plugs, tattooed fore-arms not covered with a shirt sleeves and wearing a Pikachu tee.
Now, let me say few words about the job itself. Basically, localisation testing is about finding all language mistakes and error in all localised content (that includes audio and graphics). Games that I was working with were in quite advanced stage so I had not much to do but all had to be double checked so I still needed to complete a game to the very end, exploring all possible options and features (there usually was a debugging tool that allowed to speed up the process, for instance a shortcut to instant kill of an enemy).
The issues I was finding were mostly some minor spelling errors, extra dot or comma. I had maybe on or two major bugs reported.
During my training days a lot of focus was put on cultural context. This means that localisation is not only 1:1 translation but actually porting a game to another culture. For instance, Japanese people are sensitive to issues related to atomic bombs (for instance. Fallout 3 and Megaton case); or it wouldn’t be acceptable to put nudity in Arab version.
To sum things up it was a great experience for me but I didn’t see any future unless progressing to a full-time. But all in all it wasn’t wasted time. I only regret that I didn’t have a chance to work on bigger project and in earlier stage of development.

Thanks, Michal.

GetNoticed/DajSięPoznać #00: Intro

Greetings!
While travelling to work today morning I decided to participate in this year’s Daj Się Poznać/Get Noticed competition. It is a coding contest where you need to do two things: built your individual project and blog about the project and IT.
The contest is demanding but no matter if I manage to reach the finish line or not it is a motivation and a kind of a whip that makes you work! As written in contest’s website: there’s nothing to lose. So, why not give it a try?
My project will be a program that arranges items in a sheet to maximise sheet’s utilisation. This is an issue that I often encounter in my job. I don’t know yet what algorithm I am going to use and how big the application will be. If you think about such program you can make it really light-weight with only base utility or go big and implement project management, catalogue of items, multitude of options. We’ll see what comes of it.
Here’s link to Daj Się Poznać website: http://devstyle.pl/daj-sie-poznac/
And this link leads to list of competitors: http://uczestnicy.dajsiepoznac.pl/lista
So, that’s it for now and stay tuned!

WPF: Static resources and styling

Nau mai!
Today it’s going to be about styling in WPF. So far all UIs I designed in WPF had all controls styled in their definitions. This worked sufficiently well as I have not yet built any complex application. But, it is obvious that is not to any degree an effective way to achieve styling of UI elements. My understanding of how to built bigger and more complex UI and to keep them consistent appearance-wise would be to use something like CSS in web design. And in fact WPF allows us to use similar method. Create a definition of element’s look and then assign it to an actual control in the interface.
Styles can be defined for each container. For instance, you can define style for elements in a panel, but you can also define style for whole window or even application.

Internal styles
Let’s start with styles defined inside a file where the styles are going to be used. The code below presents how to define styles available for all window elements.

In the example above we create static resources that are available for all elements in current window. Then, inside resource we create a style definition where we set style key and target type (this is optional, however to have access to control-specific properties it is recommended to do so). Now, to set specific property we use property setters where we declare a property name and assign value to it. Once, the style is defined it can be assigned to a control. The XAML code above would generate that window:

To define styles available for elements only in one container (e.g. in a panel) we need almost exactly the same code. The only change would be that the resources are set for a stack panel not for window (StackPanel.Resources instead of Window.Resources).

External resources
To reuse the same styling in multiple windows we need to create a resource dictionary. It is nothing else than a XAML file. Simply right click on your project in Solution Explorer and go Add and then Resource Dictionary.

In that file you declare styles as you like for various controls, then you put path to this file in Resources section of any container you want to style:

It is also possible to put it in application’s resources having the styles available in whole app.

In the code above there are MergedDictionaries specified. This allows to use multiple resource dictionaries in one container. If a key exists in more than one source dictionaries the last one specified will be used.

Triggers
Triggers can be used to specify certain conditions that must occur to enable the style (the most common example: a button is hovered).

The code above will make a button to change its properties if IsMouseOver property is set to true.
So, that’s it for today. I know that styling in WPF is much more vast topic and surely I will come back to it, but this basic introduction is sufficient for me for the time being.
Thanks you, Michal.

EratoWPF – Sieve of Eratosthenes (WPF and MVVM)

Hello!
I have just finished another simple app. This time it’s an application to look for prime numbers. The app is again simple but the reason for that is I wanted to make an approach to something new. This time it is MVVM design pattern.
What is MVVM? It is a software design pattern which goal is to separate user interface form application’s logic and data model.
M – model – data source
V – view – user interface
VM – view model – logic and a ‘go-between’ model and view
Use of MVVM pattern allows for a project to be simultaneously developed by a graphic designer and a coder as the UI does not (and should not) require any code-behind. Another advantage is that the whole logic and data-model can be quickly ported to new UI. Microsoft emphasises use of Blend for Visual Studio which is a graphic-design tool for creating (not only, but also) WPF user interfaces to design UIs. In this case I didn’t follow that advice. XAML editor in Visual Studio is sufficient for me.

So, how the separation is achieved? In EratoWPF case, first  I created a model which is PrimeNumbers class in PrimeNumbers.cs file. To be sure that it is working as it should I also created another project called PrimeNumbersSieveTester which is a small console application that tests the class.
Next, I started building the view in XAML with input text boxes and some buttons to run the algorithm or clear inputs.
Finally, I started building the view model. It represents the content of the UI. The view model also privately instantiates the model. The UI will not have access to it.

Binding
To allow the UI use (to display and/or update) properties from view model we use data binding. To achieve that first we need to set data-context for the UI.

The XAML code above will create an object viewModel which is an instance of ViewModel class. The code below will set main grid data-context to viewModel.

Now, to bind a property from viewModel to a control in WPF user interfaces:

The code above binds Text property of a text box to InputRangeStart property in viewModel and IsEnabled to InputsEnabled. Modes specify type of binding. OneWay allows only to dispaly data from viewModelTwoWay allows also to update data in viewModel.
This also requires a view model to implement INotifyPropertChanged. It’s quite simple:

That creates an event handler which is fired every time a property is changed. To set up a property to fire that event it is required to invoke OnPropertyChanged(“PropertyName”); method in a set accessor of this property.

Commands
As it was written earlier in this post, an application designed according to MVVM pattern should not have any code-behind. Therefore, it is required to use commands instead of events.
First, we need to create command class which implements ICommand interface:

That is basic implementation of a command. However, if a command operates on view model instance it is advisable to add private and readonly field for view model and create a constructor that sets it to viewModel defined in XAML.

After that, we need to create an instance of this command in our view model to allow it to be bound to a control in the UI.

Now, to bind the command to a control:

And that’s pretty much it. This is very basic introduction to MVVM, but good enough for a start. There are other aspects of MVVM (such as converters or dependency properties any many many more that I am not aware of at the moment) but I am sure that I’ll come to that as well. As they say: Rome wasn’t build in a day!
Good luck!

Source code: https://github.com/mickaj/EratoWPF
Readme: http://mkajzer.pl/?page_id=200
Installer: http://mkajzer.pl/download/EratoWPF/EratoWPF_installer.zip

Recommended reading (in Polish): “MVVM i XAML w Visual Studio 2015”, Jacek Matulewski, published by Helion, 2016, ISBN: 978-83-283-2867-9
http://helion.pl/ksiazki/mvvm-i-xaml-w-visual-studio-2015-jacek-matulewski,xamlmv.htm

Interfaces

Hello!
Today I’m going to write a word or two about interfaces. So, what are they? In simple words an interface is a statement that a class has certain features defined by the interface. It says that a class is equipped in certain capabilities. Here’s an abstract example. Do you recall pre-smartphones era, circa 2000? Cell phones that time had two primary functions: voice call and text messaging. But some of the fancier models had colour screen, photo camera etc. To reflect that we would say that this fancy phone is of Phone class and implement IPhotoCamera interface.
Let’s create simple Phone class with methods to make a call and send text message:

And a simplest interface I can possibly imagine:

There are few things you need to know about interfaces:
1) Interfaces can consist only of methods, properties, events or indexers
2) Implementation of methods takes place in actual class which inherits the interface. Signature of implementation must be complement with its definition in interface.
3) Interfaces can be generic.
4) Definition of a property interface includes only get; and/or set; accessor keyword without actual implementation.
5) Naming convention is to add capital ‘I’ prefix before the name of an interface.
Let’s get back to our example. Our IPhotoCamera interface contains definition of one property and one method. If a class inherits this interface it must implement what’s defined in the interface.

Now, let’s move back to our main. We can test our two classes by simply invoking methods that are available. But, there’s no use for interfaces so far. This could be easily achieved without it. Class HiEndPhone inherits after CellPhone class and could have its unique method specified without use of interfaces. But using interfaces allows us to write method specifically for objects that implement an interface that will access only what was specified in interface declaration.

But all this above is not the most important thing about interfaces. In C# a class can inherit from only one class. However, this limitation does not include interfaces. You can implement in your class as many interfaces as you want. That’s the most important feature in the concept of interfaces.
To sum things up: an interface is an indication of certain capabilities that a class must implement and actually implement; a class can implement multiple interfaces; naming convention for interfaces is to precede its actual name with capital ‘I’ letter.
Regards, Michal

MSDN: https://msdn.microsoft.com/en-us/library/ms173156.aspx?f=255&MSPPError=-2147217396

Delegates, Lambda expressions, callbacks and events

Shalom!
Since my completion of the course (read here) I have turned my focus onto delegates and events. All in order to fully comprehend the MVVM pattern. This post will be mainly about delegates and events, but I will also write a bit some of the related topics (Lambda expressions, callbacks and Func, Action and Predicate delegates).

Delegates
In short words delegates are types that can hold a reference to methods. Those methods must be consistent with delegate type signature. They can hold a named methods, anonymous methods and Lambda expressions. Interesting feature of a delegate is that its instance can hold references to more than one method which can be added/removed simply by using + or – operator. Here’s an example of delegate signature:

To create an instance of a delegate:

To invoke methods referenced in the delegate simply invoke it exactly the same way as regular methods or use Invoke(); method.

Delegate can hold references to more than one method. These methods will be invoked in the same order as they were added. If a delegate returns a value it will return value from the very last method in its invocation list.


Anonymous methods and Lambda expressions
Anonymous method is a method which is declared and its body is defined when assigning it to a delegate. Lambda expressions (introduced in C# version 3.0) are more or less the same as anonymous methods but with simplified syntax.

Lambda expressions use ‘=>‘ operator. It can be understood as ‘becomes’ or ‘goes to’. In other words what’s before the operator is inputs and what’s after the operator it output. Input and output has to be consistent with delegate type to which you want to assign the expression. If there is only one instruction after the operator and the delegate returns a value it is not necessary to use ‘return‘ keyword.

Func, Action, Predicate
These are ‘built-in’ generic delegate types introduced in C# 3.0. Generic parameters represents type of arguments and type of returned value (if any).

One of the purpose where you can use predicates is filtering a collection. For example, you can use RemoveAll(Predicate<T> match); method to remove from a list all elements that satisfy the condition.

Callbacks
While doing research about delegates it was often claimed that main purpose of delegates is allowing communication between two classes. Original meaning of ‘delegate’ noun is someone who is sent to other party with a message. And this is how delegates should also be comprehended in C# and programming.
Imagine that there is a class with a method that takes a significant amount of time to execute. To keep application responsive it would be worth to have some feedback about the status or progress of this time-costly method. It is possible to achieve via callbacks.
Here’s a Calculation class with a method simulating some lengthy calculations:

This class defines CallBack delegate type which takes one integer argument and doesn’t return any value. This delegate is also an argument in our Process method that want’s to send feedback to another class which is achieved by invoking that argument somewhere in the method.
UI for this example is a WPF window. It consists of a textbox where user gives number of cycles that Process method will run and a button that executes that method. There is also a numeric indicator of current cycle and a progress bar. Those two controls receive feedback from Process method. There is also a text box to witness that the UI is responsive while the Process method is runnind. Here’s XAML code:

Code-behind the main window consists of Click event for a button that starts the process and UpdateUI method.

Process method is started as a new Task to keep the UI responsive. UpdateUI method must have signature consistent with CallBack delegate defined in Calculation class as this method is used as an argument in Process method.

Events
Concept of events enables a programmer to use a kind of notification system between objects. To depicts that I prepared small program that imitates a wallet and adding money to it. Here’s listing of Wallet class:

First of all it has a delegate GotSomeMoney declared that defines event handler signature. Event handler is a method that is executed when an event occurs. It takes two parameters: object sender (which is an object that fires the event) and EventArgs e  (object of an EventArgs class that holds argument that you want to pass with the event).
At the very end of the file above I declared a new class MoneyEventArgs which is derived form EventArgs class. This class has two properties that will be passed with the event.
Having these two parameters in event handler is to follow the .NET guidelines. It is not necessary but if you take a look at all the events for all of the controls (in WinForms and in WPF as well) you’ll see that they follow the same guidelines.
Now, if you analyse setter for Money property in Wallet class you will notice that FireEvent method is executed in some particular circumstances. This method takes one integer argument. Now, if we move on the the code of this method that it creates new instance of MoneyEventArgs class and assign certain values to its properties. Then, it checks if there are any subscriber for the OnGotSomeMoney event and if affirmative it fires the event with this as an object argument and that newly created instance of MoneyEventArgs class.
Now, let’s move to the UI. It has a text box to provide owner’s name and a button that initializes new instance of Wallet class. It also has a counter that displays content of the wallet and buttons that allows a user to add some money. The are disabled until the initialize button is clicked. Here’s XAML code:

This XAML code also defines myWallet instance of Wallet class. It all happens in <Window.Resources>. This instance will be available also in code-behind.
Now, let’s take a look at code-behind:

Code-behind has ThisWallet_OnGotSomeMoney method which signature is consistent with GotSomeMoney delegate in Wallet class. This method will be assigned as a subscriber to OnGotSomeMoney event of thisWallet instance by clicking Initialize button. Note, that this assignment is achieved by using ‘+=’ operator. To avoid clearing all subscribes it is not possible to use ‘=’ operator event. You can only subscribe to event by using ‘+=’ or unsubscribe by using ‘-=’ operator.
ThisWallet_OnGotSomeMoney method takes some values from sender and MoneyEventArgs and creates some strings that will be displayed in a message box when the event occurs.

Understanding all of these concepts required to be quite focused and multiple reading or watching of the sources I had available. If I were to recommend something that helps to understand these aspects of programming here are some links:
Jesse Dietrichson: https://www.youtube.com/channel/UCiA3tURI8dwCOUzCeM90c2g
https://www.youtube.com/watch?v=8e2GEFNctwQ&t=1466s

.NET Interview Preparation Videos
https://www.youtube.com/channel/UCHI5xgQujSyqz_UyKdLFaqw
https://www.youtube.com/watch?v=ifbYA8hyvjc&t=416s

All of the code presented in this post can be found here:
https://github.com/mickaj/DelegatesLambda
Feel free to test it!

That’s it for today. Next, I will post something about interfaces. Hopefully, shortly…
Regards, Michal