I’m back and Git – rookie’s thoughts

Hello there!
It’s certainly been a while since my last post! It was more or less 6 months ago which is a long time but I wasn’t idle, oh no! If you briefly scan all my posts you’ll notice that my field of interests was Windows apps, mostly WPF technology and MVVM pattern. However this has recently changed – I’ve started ASP.NET app! The project is a web app for acquainted company which purpose is to organise and keep track of service jobs they provide to their client. It is not an open project so I can’t share the code at the moment. Let me say only that it is an MVC app using what comes by default with an MVC template in Visual Studio (Entity Framework, Identity, bootstrap, jQuery etc.) so as you can see a lot of new things!

Here you go a screenshot of the early version of the current app (first version is up and running, but it is very very basic so they have anything to start with). Let me stop here about this project and let’s move on to the next thing which is:

Git – my first thoughts

So, I’ve already been using GitHub (here’s my account) but recently I did a quick course on Git (on LinkedIn Learning [link]) so I thought why not to try it on my own. So I downloaded packages, created separate partition on my hard drive and installed it and started using it. As I’m a beginner I use only some basic commands that you definitely know:

  • git status – shows current changes and what’s been staged
  • git add .  – adds all changes to commit stage, the dot indicates that all files must be added, you could replace it by a specific file name
  • git commit -m”<message>” – commits staged changes to a repository with a message, I generally try to always commit with a message
  • git commit -am”<message>” – adds to stage all changes (except new files) and commits them to a repository
  • git log –x – prints out a log of a commit where x is an ordinal number of a commit (1 – is the newest)
  • git push – pushes (uploads) all commits to a remote repository

And that’s more or less it. That’s enough for me to start.
Now, a word about remote repository. You can use GitHub to host your remote repositories, they offer unlimited number but in a free plan they can only be public repositories (it’s easy to find how to set it all up on their help pages). If you’re looking for a private repo you can simply use your local drive (once you have a directory set up simply run git bash, navigate to this directory and execute git init, or start your project in Visual Studio and tick the Create new Git repository option). However if you still need the remote repository to push your commits (for instance to share the source code with others working with you on a project, or for backup) what you can do is to use Visual Studio Team Services . They offer private repositories. To set a remote address for your repo in VSTS you need to:
a) once you are registered and logged to VSTS you need to create new project with version control set to Git
b) go to https://xxx.visualstudio.com/_projects where xxx is your alias and click on your project’s name, this will bring you to project’s homepage
c) unfold second category as below
d) execute the above commands in your git bash (of course your URL will differ)

It’s all set! This basically links your local repo with a remote repo at VSTS. In the above command ‘origin’ is a name for the remote repo. If your case is that you use only one remote repository you don’t need to specify it when executing the push command in future.
So, that’s about it what I wanted to say about my first steps with git. Maybe as a side note I’d add that help files that come together with git installation are really really helpful so I encourage to look for solution there in case you encounter any problem.

One-bytes #3: Methods returning multiple values or the Tuples

*** #3.1 How to return multiple values from method***
Quick one today – how to write a method that returns more than one value. There are two ways: i) use out keyword, ii) use generic class Tuple. In the first approach we return first value as we usually do, the second value will be passed as parameter with out keyword. Take a look at example method:

Now if we want to make use of this method we either need to have a variable pre-declared and pass it into the method or declare it inline in the place of invocation:

Nice and simple, right? It the second approach we make use of Tuple generic class. It works with up to 8 generic parameters meaning that we can return 8 values (but nobody says that one of the returned values is another tuple, so in practice we can go for how many values as we want). Here’s an example:

So this method in fact returns one value of type Tuple. So how to access the values we really want?

Again, nice and simple. Which way is better? I guess the one you prefer 🙂

Tuple Class on msdn.com

One-bytes #2: Selection in WPF, OnPropertyChanged parameters

*** #2.1 Item selection in WPF selector-enabled items control***
In WPF we can use multiple types of controls to display collections of items which allow user to select one or multiple items from the collection. In this post I’m going to discuss what single selection possibilities they offer.
Let’s start with inheritance hierarchy – controls that allow such selection inherit from System.Windows.Controls.Primitives.Selector. If we take a look at what properties they have we find four that may be involved in selection process:

  •  SelectedIndex – Gets or sets the index of the first item in the current selection or returns negative one (-1) if the selection is empty.
  • SelectedItem – Gets or sets the first item in the current selection or returns null if the selection is empty
  • SelectedValue – Gets or sets the value of the SelectedItem, obtained by using SelectedValuePath.
  • SelectedValuePath – Gets or sets the path that is used to get the SelectedValue from the SelectedItem.
    source: msdn.microsoft.com

So, there are three ways get the selected item: i) its integer index in the collection, ii) the item itself, iii) one desired value from the item. 
I have prepared a quick demo to show that. The app displays a ListBox of custom class objects and once an item is selected displays all three ways to present the selection. Let’s take a look into the code, starting with the class of objects that our list will contain:

The list will be generated and stored in view model. The view model will also have three public properties: i) ItemSelectedIndex of type integer bound to SelectedIndex property of  our ListBox, ii) ItemSelectedItem of type Item bound to SelectedItem, iii) ItemSelectedValue of type string bound to SelectedValue. Let’s take a look at complete ViewModel class:

And now the most important part – the view. As mentioned above as a container for collection we will use ListBox and bound properties as it was described when discussing the view model class. The only thing that’s left is setting correct value to SelectedValuePath property. In this case we want to use Name property of our item class so we need to set SelectedValuePath to “Name”. Here’s how to set the ListBox up:

Now, to use the selected index, item or value which are bound to corresponding properties in view model we need to add some controls and again bound them to view model properties:

And that’s it. To sum things up – there are three ways to access selected item in a selector control in WPF: by its index, by the item itself or by one particular value in the item.

*** #2.2 Passing property name to OnPropertyChanged()***
Second thing I want to mention today is a hint how to make invoking OnPropertyChanged() method in a property setter a bit more controlled when not using any MVVM framework.
ViewModels usually implement INotifyPropertyChanged interface which purpose is to notify views when a property has been updated. This is done by invoking OnPropertyChanged method with property name passed as a parameter.

That is not the best way. What if we decide to change the property name and the backing field can also be changed somewhere else? In this case we need to go and manually change the hard-coded property name. So what can be done instead is this:

Having passed the parameter this way we can simply go to the property, right click and rename it using Visual Studio renaming tool which will update all calls to this property. Definitely better!

Design Patterns #10: State

Design patterns episode 10 – State

Happy Christmas!! Isn’t it a good time to write a post?
Let me start with an apology. In previous post about patterns (composite) I promised to keep that one week/one pattern schedule but as you can see I have failed. But in the meantime I posted something different (one-bytes #1) so I feel forgiven to some extent. Learnt by experience I promise nothing this time. With that being said we can proceed to the next pattern.

Today’s hero is the State. We all know those simple machines which operation model is frequently very simple but closed within exact patterns. For instance the example given in Head First book – a vending machine. It allows only two or three possible interactions (insert coin, get coin back or get the product) and serves one particular purpose (sell products). Its operation model is base on states: the machine can have a coin inserted, can be out of products, etc. So the machine changes its internal state and this change implicates change of behaviour.

DEFINITION
Let’s take a look at the definition and the diagram.

The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004) 

In object-oriented programming the above definition is realised by representing these internal states by different implementations of one interface (or inherited from an abstract class). The important thing is the fact the state changes internally. It is not possible to set state from outside. If we go back and think about strategy pattern we will probably see that these two pattern are similar but that closure to changes from outside is what makes them different.


This the diagram depicting the state pattern and similarly to strategy pattern we have encapsulation of behaviour in a separate class: behaviour of Operation() method in context class is encapsulated in state object. It is possible to have multiple states but transitions between them must be done privately. User of state context must not be able to enforce the context to switch state in any other means than normal operation on the context, intended by designer. We don’t have any public method to set the current state from outside. And that is the key to state pattern.

EXAMPLE
I have used a prepaid electricity meter to show the pattern. It can be thought of as a state machine: it can be switch off, switched on but idle, conducting electricity to appliances or be out of credits. Let’s start with the meter interface:

It exposes two properties: one is the credit that the meter is topped-up with, the other is current state of the meter. Both of them are get-only: there is specific method to top-up and the state cannot be set from the outside. Other than that we have methods to turn the meter on/off, start delivering power (for specified number of cycles)  and already mentioned TopUp() method.

The implementation of the meter is slightly more complicated. First we need to equip properties from the interface with setters. Next we need properties for each of the possible states. In this case there are three states: OnStateOffState and MinusState. Other than that we have methods to manipulate with credit and a constructor. This is important: we initialise state instances, set credit to zero and set current state to OffState. The last step is four methods from the IMeter interface. These methods don’t have their own implementation but they call current state object to execute its corresponding operations.
Now the abstraction of state class. In this case I’m using abstract class because I need some not public members, force the inheriting classes to set reference in constructor to the meter the state is going to be used with, and reuse some common pieces of code.

As you can see states will have all the methods that the meter will call in different states. The TopUp() methods has default implementation because it will the same for OnState and MinusState, method ReachZero will be called whenever the meter runs out of credit. It doesn’t need to be virtual because no override will ever be needed.
The last pieces of code would be actual implementations of the sates. Let’s take a look at just one:

As you can see each state provide its own implementation of actions possible for the meter (except for TopUp() which as stated earlier can be shared and in this case it is, but it isn’t in OffState where it is overridden to simply write out on console that the meter is off). Note that some of them changes the state – that’s the core of this pattern: the internal change of state.
Having all the states implemented we can see how it works:

The above would generate output like this:
As you can see we invoked Start() method on one and the same object and we got three different results which all depended on the state in which the object had been, and some of which changed the state of the object. That’s the way how the state pattern works.

Before I prepared this example I had prepared another: a model of vending machine. It is a WPF app. The reason I decided to go for something different was the fact that it had become a bit unclear in the code. Simple console app is much better to illustrate the  pattern. However I did not abandoned the code and you can take a look at this as well. Here’s quick video how it works and the source code you will find at the bottom of this post.

So that’s it for today. Hope you like it 🙂 Before you go please find some useful links below. Enjoy!

Source code – IMeter: TXT file
Source code – Vending machine: GitHub

Design Patterns #9: Composite

Design patterns episode 9 – Composite

With unexpected delay but patterns are back! In this episode – composite.

The composite is generally used to model tree-like structures in a way that classes that are using the composite can handle its elements in one particular way without having to distinguish whether an element has children – a composite, or hasn’t – a leaf (in other words, whether we can go further down the tree or element is a dead-end).

The first thing that comes up when thinking about that kind of structure would be a directory tree where folders are composites and files are leafs. Or any other structure alike: corporate structure (managers and subordinates), online shops (categories and concrete items) and many many more.

DEFINITION
Let’s see how the Head First book defines this pattern:

The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets client treat individual objects and composition of objects uniformly.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004) 

So, in other words we have tree structure of objects and collection of objects and the client doesn’t need to care about if it’s a leaf or a composite. This is the key feature of this pattern. For instance, let’s think about file system where we have files and directories. Both of them are elements of file system and should be treated the same: the client can perform the same operations on both – rename, delete, get size etc. But obviously we can do more things with directories (as this is a collection of files and directories), therefore composite pattern isn’t applicable here (of course you could use typecasting to make it work but that’s a different thing).
The diagram shows what discussed above – both concretions are treated the same, nothing different can client do with one or the other type. The diagram presented here is different than what’s in the book. The book adds further methods: add()remove(),  getChild(). But isn’t that inconsistent with the definition? How can you add a further child to a leaf? You could throw an exception but wouldn’t that violate the Interface Segregation Principle? That kind of issues have been greatly discussed here by the guy who I quoted on multiple occasions.
So, to conclude this aspect of the pattern – my opinion is that we should stick to ISP and not force any class to implement something that the class doesn’t use. Period. Let’s move on to code example.

EXAMPLE

In our code example we’re going to build a store’s menu. Let’s start with the abstraction:

Our IStoreElement consist of name property and a method to list self in the menu: there will be different implementations of this method for leaves and composites. This method can take optional argument as we want to nicely format the menu by indentation of sub-components.
Now the leaf class:

Leaf’s implementation of ListOut() method works that it returns a string with given number of dashes and its name.
And finally composite class:

This class is equipped with private list of objects that implement our base interface. This list can be set in constructor.
The ListOut() method starts with the same thing that counterparting method in leaves but before returning the value recursively invokes the same method for all IStoreElements that the composite holds in its private list. This invocation takes indent parameter increased by 1. This way we achieve that nice formatting of the list once requested in the topmost component.
Now, let’s see how it work all together:

We generate the list and then print to the console the string returned by ListOut().

To sum things up: he Composite Pattern is used to represent tree-like structures where all their elements can be treated uniformly, where single components are called leaves and collections of components are called composites. The pattern can be equipped with methods to modify the content but this lead to violation of Interface Segregation Principle.

Next week: the State Pattern. I hope that this time without any delay. Check the links and source code below. Thank you!

Composite pattern by Christopher Okhravi: link [YouTube]
Composite vs. Decorator by Christopher Okhravi: link [YouTube]
Composite pattern by Michael: link [YouTube]
Source code: TXT file

Design Patterns #6: Adapter

Continuing with design patterns. Time for Adapter. This pattern is a structural pattern whose purpose is to convert interface (in a meaning of public members of the class, not necessarily interface as a programming language feature) so the class is usable with client’s code. The Head First book defines this pattern as:

The Adapter Pattern converts the interface of a class into another interface the client expects. Adapter lets classes work that couldn’t otherwise because of incompatible interfaces.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004)

Generally, it may be said that the adapter pattern wraps an object that cannot be used by a client and exposes an interface that allow the client to use that object. Let’s take a look at the diagram:

So, we have a client that wants to use an object that implements IExpected interface, however we already have a class that does what we need but doesn’t have a compatible interface (unsupported class). So, to solve the problem we need an adapter. The adapter will have all public members that the client expects – will implement the IExpected interface and at the same time will privately wrap an instance of unsupported class (passed in a constructor, for instance). Once the client calls the adapter, the adapter will in turn call the wrapped unsupported class and return results to the client (and if required convert them to what the client expects). And that’s it, simple as that.

EXAMPLE
Let’s take a look at code example now. We have a class that calculates area and perimeter of a rectangle. (These calculations are very simple but to give the example a little bit more depth think of them as of very sophisticated and complicated). That class operates on double type. Our client, however wants to calculate area and perimeter of squares only and operates on integers. We could i) write a new class to handle that but we don’t want to do that because we already have a class that is capable to perform such calculations (square is a rectangle after all, right?); ii) modify our client to work with the existing class, but again we don’t want to break anything elsewhere (OCP right?). That’s why the right solution here is the adapter.
Let’s compare what we have and what we need:

So, the differences are: i) types (already mentioned int vs. double), ii) method names, iii) number or arguments required for counterparting methods.
Now the adapter. First of all it needs to wrap the already existing class and set its instance by passing it through constructor; then we need to implement methods required by IExpected interface in a way that they call the wrapped object and return values converted to integers.

Let’s write a quick test:

Everything works perfectly.

Object adapter vs. Class adapter
The explanation and code example is an object adapter. This means that the adapter works with a concrete instance of adapted object. Advantage of this solution is that this type of adapter will work also with objects of classes which are derived from adapted superclass.
There is also another adapter-type pattern called class adapter. In this type you don’t need an instance of adapted class, instead the adapter class inherits from both: expected class (or interface) and adapted class. Remember that inheriting from more than one superclass is not possible, what could be done is to create new class that inherits from a class that needs to be adapted and implements expected interface. This approach may also be useful but keep in mind that it looses the advantage of composition over inheritance.

To sum things up: adapters are extremely useful everywhere there is a need to use something that can do what we need but doesn’t have compatible interface.
Plan for next week: Facade

Don’t forget to check the links below!

Christopher Okhravi about Adapter Pattern: [YouTube]
Source code: [TXT file]

Design Patterns #3: Decorator

Design pattern number 3 – decorator. The decorator allows to dynamically modify behaviour of an object, and by ‘modify’ I not necessarily mean to swap completely.
The idea behind decorator pattern is that you take an object and wrap it with another object. Calling the outer object (decorator) will in turn call the inner object (component) and before returning any value will do its part with the value.

The example given in the book is a coffee shop where base coffee can be decorated with multiple toppings such as cream, sugar etc. And all those addition will make their own impact on price and name. The important is that the base product (component) and the decorator implements the same interface, the difference is that the decorator has a reference to the component.

And while the decorator itself can be a component it also can be decorated. And so on, and so on… Let’s take a look at the exemplary diagram: the decorator implements the component’s interface and has a reference to a component (we can say in short: the decorator has a component and is a component).

CODE EXAMPLE
Let’s now move on to the code example. My example will be similar to one presented in the book – orders that can be decorated with discounts, extra costs etc. So let’s start with abstractions.

Abstractions
Our IOrder interface will have its name and cost. Decorator interface will extend IOrder with property of IOrder type with public getter only.

Implementations
Concrete classes will be very simple. Order class will have two automatic properties (with private setters) and a constructor that sets those properties.

Things get a bit more complicated with the decorators. Here I will describe only one example but in the source code linked at the bottom of the page you will find two more (however they are very similar). The most important difference (as indicated already twice in this post ;)) is that the decorator has a reference to IOrder object. It will be set int he constructor. As this decorator’s purpose is to apply discount  to the order we will need another property for that (of type int and it will also be set in the constructor). Now the essence of the pattern. As the decorator itself is of type IOrder we need to implement Cost and Name properties. These properties will call counterparting properties in referenced IOrder object, get their values and modify them appropriately. In this case the cost will be reduced by discount value and the name will be equipped with a suffix informing about the discount. We can build as many decorators as we please, and use them as many as we please.

Usage
To test our orders and their decorators we’re gonna instantiate a pack of orders, decorate them and decorate again. They all will be stored in a list and then we will iterate through the list and print to screen their names and cost.

All works perfectly:

That’s it for today. Next week it will be time for factories. So I hope we see again!

Source code: download txt file

Design Patterns #2: Observer

Dzień dobry!
Continuing on design patterns – it’s time for the Observer. This pattern allows linkage between one observable and many observers that when the observable changes its states the observers are automatically notified and updated. So, the observable has a collection of observers, it performs its actions and when certain defined event happens it notifies its own observers. Let’s take a look at the diagram:


Let’s start with the observers: their interface defines only one method: Update(). That method returns void and can take parameters. In fact parameters are used to notify the actual change and not only the fact that the value has changed. It will be later shown in the example.
Now the observable: it must have possibility to add and remove observers (Register() and Unregister() methods respectively, as an argument they take  object that implements IObserver interface) and to notify its observers about the change. Concrete implementation of the observable also has some sort of observers collection. (This collection is not part of the interface because a) it doesn’t have to be public, b) methods to register and unregister the observers are exposed publicly and that’s enough for the client, it doesn’t have to know how references to the observers are stored. Of course it doesn’t have to be like that. What we’re discussing here is just the pattern and its actual implementation may vary depending on every particular need.) Usual implementation of Notify() is iteration through the observers collection and invoking Update() method on each of them. And that’s it. Let’s go with the example.

EXAMPLE
Example given in the book (previous post explains what book) is a weather station (measures temperature, pressure etc.)  and several types of display (current conditions, stats etc.) I think that’s a really good example but our example will be simpler but similar to some extent. We’re going to build number generator and two types of display.

Interfaces
Have a quick look at the code below:

Hey, where’s Notify() method?! We don’t want that method to be exposed publicly therefore it won’t be here in the interface. As said earlier, the design patterns are not exact implementation nor have strict code structure, they are more of a general ways to achieve some result. But if you hear from another developer that he has used the observer pattern (or any other pattern) you will instantaneously know what to expect.
IObserver interface defines only one method which is Update() that takes one integer parameter which will be passed to our observers.

Concretions – Number Generator

Our number generator will – surprise, surprise – generate random numbers within given range (which is specified by constructor’s parameters). It has list of objects of type IObserver and two methods that allow adding and removing from that list. Method notify() is private as we don’t want to make it possible from the outside of the class to force the observable to notify its observers. This method (as you can read above in this post) simply iterates through observers collection and invoke Update() method on each of them. This method is invoked inside Next() method which generates next random number. Parameter of the Update() method is last generated number.

Concretions – Observers

These two implementations of IObserver using their Display() method print their current readings to console. One of them displays aggregated value of all random number passed from the observable, and the other displays average value. Their Update() are consistent with the interface they implement.

Wiring all together
All the above classes will work together in this small console app.

As you can see once we have an instance of NumberGenerator we can register some observers. Our console app will iterate 10 times and draw 10 random numbers and display readings of our observers.

Self-registration/unregistration
The example above shows basic implementation of the observer pattern. It may be improved by allowing object to self-register/unregister. This can be simply done by storing reference to observable in the observer. In this case observer will need appropriate methods: to register that takes observable as an argument, and to unregister with no arguments. Let’s take a look at its interface:

It extends existing IObserver interface and adds two methods as described earlier. Now, the concretion:

So, it now has a reference to the observer which initially is null. When we want to self-register it to a particular observer we simply invoke SelfRegister() method and pass the observer as an argument. The method will save the reference to the observer and invoke observer’s Register() method with this passed as an argument. SelfUnregister() method performs opposite actions. The code says it all 🙂
Below you will find to txt file with the source code. Thanks for today, and hopefully see you next week. Cheers!

Source code: download txt file

Design Patterns #1: Strategy

Nau mai!
Time for design patterns. Whenever I tried to find out anything about them I encountered this pretty good explanation what are they and why we need them:

Someone has already solved your problems.

‘Head First Design Patterns’ (page 1)

And after Wikipedia:

In software engineering, a software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system.

[source]

In a nutshell: common solutions to common problems. And that should be sufficient to start with first design pattern: Strategy. But, before that quick introduction to this series. It is inspired by Christopher Okhravi and his playlist. I will do basically the same: go through all design patterns in Head First Design Patterns book by Eric Freeman, Elisabeth Freeman, Bert Bates and Kathy Sierra. I have Polish edition but that does not make any difference for you, I will not give any quote in Polish (probably I won’t give any quote at all). To make this series somehow different and not to copy either the book or videos linked above I will use different examples. So, with that being sad we can cut to the chase.

Definition
Strategy defines common abstraction of set of algorithms, encapsulates them and make them reusable and interchangeable in run-time.

How is that achieved:

  1. Define abstract class or interface that has one common method which invocation will perform some action
  2. Define concretions for the above
  3. Add variable of type strategy abstraction to your client class
  4. Add method in your client class which will execute strategy
  5. Add method in your client class that will allow to change strategy

    And that’s basically it. Now, let’s move to example.

    Example
    Example given in book is a duck simulator. It uses different types of duck where actions such as quack or fly are abstracted and encapsulated into strategies. Good example in my opinion. Our example is magic box that consist of an array of 10 integers which can be displayed in console. But the way the numbers are displayed varies depending on enumeration strategy. Let’s start with abstracting the enumeration strategy:

    So, our strategy is used to return string that enumerates all numbers in given array.
    Now, let’s implement different strategies: enumerate as is (without changing the order), bubble sorted and shuffled.

    What could be done better in those three implementations is that part of the code that build output string is common so natural reaction would be to encapsulate it somehow, but please, turn a blind eye for that 🙂
    Next step – writing our MagicBox class which has an array of 10 integer, randomly generated in the constructor, private field of type IEnumerateStrategy accompanied by a method for changing the strategy, and Display() method that writes numbers to the console using the strategy.

    To test the example in application’s Main() method, we will create new MagicBox object and assign new AsIsEnumeratorStrategy, then invoke Display() method, and then assign some other available strategies and again invoke Display() method.

    So, as a result we get number listed using three different strategies. Advantages of using Strategy Pattern is that you can write as many strategies as you want without changing the class that uses them and interchange them during run-time (the definition, right?).So that’s it when it comes to Strategy Pattern. If you’re interested in next pattern (which is going to be the Observer) please come back (probably) next week. Thanks!

    Source code: download zip file

User-defined value type

Hello there!
Something basic today: how to write your own value type. In C# we distinguish two kinds of data type: value type and reference type. The former is a) stored on stack, b) is by default it is passed as an argument by value; the latter is a) stored on heap and only its address is stored on stack, b) is passed as an argument by reference. At this stage the important thing that is needed to know is that point a makes impact on performance [more]; point b makes impact of how data is circulating through methods. If an argument is passed by value only the value will be taken into the method and, we may say, the link between variable name and its value will be gone from method’s point of view, this means that the original variable cannot be modified by the method. If an argument is passed by reference that link will still be valid meaning that whatever changes a method do to the data it will be reflected everywhere that data is used. The code below will make it much clearer:

The output of the above would be:
As you can see modifications to our list of strings which is a reference type have been done to our object, however our integer variable which is a value type have not changed because only its value was passed to the method. That’s the main difference. The good thing to know is that value types can also be passed by reference – to do that we use keyword ref before an argument we want to pass by reference. This keyword must be present both in method signature and in its invocation place.

And the result:
So, that explanation is enough. We know what is the difference between value and reference type and what implication does that difference bring to behaviour of these types. Now, let’s move on to our custom value type. These are basically structs. They (similarly to classes) can consist of fields, properties, methods etc. and struct’s members can be static, but the struct itself cannot be static. Another important feature is that a struct cannon be derived from a class (that’s obvious) or another struct, however they can implement interfaces.

Our value type will store coordinates assuming that point 0,0 is the bottom left corner of our plane – this means that only positive values of component X and component Y can be assigned. This is due to way of how our value type will be assigned:

So, let’s start with required properties for X and Y coordinates, and distance from point 0,0. That’s simple:

Now, time for constructor. What it is actually going to do is decomposition into two coordinate component. It is also going to be private as we won’t be creating variables of this type using the constructor but simply by assigning a double.

This decomposition is achieved by using some of the static methods of Math class [see here].

Now, the fun part: how to make it possible to assign double value to our struct using ‘=’ operator? Simply by defining new implicit conversion operator that will use already defined private constructor to create an instance of our struct.

Next step would be to override three methods: ToString(), GetHashCode() and Equals() methods. A word of explanation here: although a struct is a value type it is derived from ValueType type, which in turn is derived from Object, and despite the fact that it is not necessary to override those three methods we want to be sure that they will act as we intend: ToString() will return X and Y components separated by comma, GetHashCode() will return hash code for double created based on X and Y, and Equals will check if the argument is of our user-defined type and if it does the method will compare X components and Y components:

And now we’re at the point where we could stop. Having the above done is enough to use our struct but we want to override some of the operators to make it easier to use. We will override pair ‘==’ and ‘!=’, and ‘+’ and ‘-‘ operators. For the comparison operators we assume that our structs are equal if both counterparting components are equal, for addition and subtraction we will add or subtract components X and Y:

And that’s it. Our user-defined value type is ready to use. Of course we could override more operators and I guess is-bigger-than and is-lesser-that would be a good idea but it’s easy to do so if you want to extend the struct your good to go. Below you will find complete code for all above and code for unit tests.

Regards, Michał!

Coords
Tests