Saturday, July 28, 2012

Multi Plaftorm Targeting using Portable Class Libraries - An Introduction

I have been putting off the discussion about portable class library tool for a long time now. But since Microsoft has released RC2 of the tool this month with exciting new features, it is very appealing to carry the message forward to followers of my blog.

Multi-platform targeting has been a big issue when we want to reuse our code for these platforms. It is common when we are working on a rich UI application with Silverlight and WPF interfaces. It has been so difficult to reuse our code because of incompatible class libraries. Silverlight does not support regular class libraries targeted for Windows platform and we need to create separate Silverlight Class Libraries.

Existing Workarounds for Multi-Targeting:
There are several workarounds developed to cope with this issue. One of them is project link. We create links between project to use types from the other project.

Project Linker:
This is a Visual Studio Add-on provided by Microsoft P&P. It makes life easier for linking the project items in multiple projects. If we link a project with another project, then if an item is added in the source project, the same item is added to the destination project. For a long time, developers have used this to be the only option for multi-targeting to WPF and Silverlight projects.

http://msdn.microsoft.com/en-us/library/ff648745.aspx

This can be downloaded from Visual Studio Gallery from here:

http://visualstudiogallery.msdn.microsoft.com/5e730577-d11c-4f2e-8e2b-cbb87f76c044/

Once installed, it can be used to add a project link to a destination project. Just right click a project and select Add Project Link. You can then specify the source project.


Adding Existing Item as Link: . This is the same thing as "Project Linker" does. It is just doing the same thing manually. Add an item in source project. Go to destination project, add existing item and make sure that you add it as link.

Pre-requisite:
Visual Studio 2010 sp1 or Visual Studio 2011 can be used to create portable class libraries. We do need to install Portal Library Tools. It can be downloaded from Visual Studio Gallery [http://visualstudiogallery.msdn.microsoft.com/b0e0b5e9-e138-410b-ad10-00cb3caf4981]


We can also use Extension Manager to install Portable Class Library.


Installation On Build Machines
In this time and age, you wouldn't find an organization with no Continuous Integration [CI] support. Mostly they use Jet Brain's Team City or Cruise Control .net. The pre-requisite described above are for development machines. Portable Class Library tools can be installed on build machines using /buildmachine switch. From msdn:

Run the installation program from a Command Prompt window, and include the /buildmachine switch on the command line.

Creating Portable Class Library Project
After installation of extension in Visual Studio 2010 Sp1, a project template is added for creating portable class library project. It is also available in Visual Studio 2011. We can find it in Add New Project dialog as follows:


While creating the project, an option is provided to select the required target frameworks. We can select the supported .net, silverlight and WP frameworks. It also supports the selection of XBox 360 and Metro Style App support.


These options can also be changed later on from the project's Properties page. Please notice the new Library tab available. Here we can select the target frameworks. This is equivalent to Application tab of .net framework class library where we can select the target framework.


Please not that there are other tabs too which are not available for portable class libraries.


Feature Set & Selected Frameworks:
The feature set available for portable libraries depend on the selected target frameworks. There is a universal set of feature supported by all the frameworks which are possible targets. Out of these universal features, each individual framework would support a subset.

It is very tempting to select all available frameworks for target. But doing that is limiting ourselves. As described above each framework would only support a subset of available features. Selecting multiple frameworks would make only the intersection of the features of supported frameworks. In the following example, we are selecting the .net framework and Silverlight as target frameworks. The available feature set is the overlapping area between two circles [Remember Venn diagram from your statistics courses :)]. If this is .net framework 4, then the library wouldn't have any view model support.


This could be further limiting if we select other frameworks.


Selecting all frameworks would only provide the little overlapping features supported by all frameworks.


This shouldn't be a limiting factor for your development. The library which is supposed to be shared across different platform would never have such code which have a dependency for a particular framework. The selected frameworks is basically an indication that the code is generic enough that it could be shared across these platforms.

The following subset is available for Silverlight 4, .Net for Metro style app and Windows Phone 7 platforms.


The following is the list of available libraries for the multiple targets of .net framework 4.0.3, Silverlight 4, Windows Phone 7, .Net for Metro style apps and Xbox 360.


Please not that if there is an additional framework which could also be selected without any effects to the available set for the selected frameworks than it is automatically selected.


Referencing Portable Libraries and Portable Library References:
Portable libraries cannot add references from non-portable libraries. Here ClassLibrary1 is a .net framework 4.0 class library. An attempt to add a reference to the portable class library causes the following:


Portable Library references can be added to regular libraries belonging to the supported frameworks. The same error message is displayed if an a portable library's assembly references is being added to an unsupported framework.

Thursday, July 26, 2012

DataTable & WCF Service

In this post we will be discussing a minor issue with the serialization of DataTable in WCF. We, then would present its solution. The issue is that we cannot send a DataTable object across the wire for which TableName property is not set. If we do try to send it, it throws exception. The post would just have an example to show the issue and its solution.

There are a lot of material you can find, not recommending DataSet and DataTable on WCF boundaries. But you might run into situations where some architectural design decisions are horribly taken and you cannot change them. This case would be one of them. Or this might be a client requirement which needs data in this format.

Let's create a WCF Library project DataTableWCFApp.Service. We can update the service contract as follows:

We can use the following as the implementation of the ServiceContract interface presented above. This is just creating a untyped DataTable, filling it with a single row and returning it.

We wouldn't be able to test it using WCF Test Client because of non-primitive DataTable type which it cannot deserialize.


So let's create a simple MVVM Light WPF project to test it. Here we are creating a project with name DataTableWCFApp as follows:


After adding the service reference for the DataTable Service, we need to update the view and view model for showing the DataTable returned from the service. Let's update MainWindow as follows:

So the view expects a collection MyData in its DataContext. The collection is expected to be available at the time of loading the view, hence OneTime mode for Binding. Let's update the view model as follows:

Before running it, we need to find a way to host the WCF Service. Luckily Visual Studio makes it easier for us. Just check the following option is checked for your WCF project. This would host the WCF Service when another project in the solution is being debugged. If we set the WCF Service project as the start up project then this would host it in WCF Service Host, additionally, this would launch WCF Test Client for the service.

Now set the WPF Project as the Startup Project and run it. We get the following CommunicationException with no details about what actually happened or how to fix it.

In order to find the actual cause, let's take some help from WCF Service Trace Viewer. We need to add the following configuration in our WCF Service project's app.config file.

Now we can run it again. We would again get the same exception but the traces should be recorded in the location for the trace file as mentioned in the above configuration. Let's try opening the file using Microsoft Service Trace Viewer. We need to install Windows SDK for this tool. It shows the actual cause of the problem.
The error message is descriptive enough. We are just missing to set the TableName of the DataTable. The DataTable cannot be serialized without setting it. Let's update the Service to do the same as follows:

Now we run the project again. Now the service returns the response without any issue. The DataTable is used by the view to display it in a DataGrid. For an untyped DataTable, this would be the most suitable control as this can analyze data and create columns based on the data in the DataTable. Other control, e.g. ListBox would show DataRowView for each entry in the DataTable.


Download

Tuesday, July 24, 2012

Singleton - Le Problème

Singleton is presented as one of the Creational pattern in Gang of Four's famous Design Patterns: Elements of Reusable Object-Oriented Software. It is described as the pattern used for restricting the instances of a class to just one.

Like Service Locator, Singleton also has this issue that it results in shared state across the application. The same object is being shared across the application which might lead to threading issues. The other issue with singleton is the way the shared object is provided. It is provided as Instance static property in the same class. Its type is same as the type it is contained in. All the other code consuming this singleton would be using the Instance property to access the only available instance of the type as the constructor is private. This makes it impossible to unit test the other code specially if the singleton is sealed for inheritance and Instance property in non-overridable (non-virtual). This is because we can not create stub or mock of this type to set expectations and override them.

In this post, we are discussing different approaches to singleton and their comparison. We will be discussing the general issues with singleton. The discussion would then be followed by some brief discussion of incorporating unit testing while keeping the existing singletons in our design.

Eager Initialization
This implementation of singleton structure is commonly referred as eager initialization but the way static initializers are executed in C#, it is not so much eager. With static constructors, the intitalizers are executed just prior to the static constructor. The compiler would guarantee laziness because of static constructor by not marking it with beforefieldinit flag.


This is what C# 4 Language specification has to say about the execution of static field variable initializer. It happens before the use of a static field of the class. Excerpt from C# 4.0 Language Specification:

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

Since Authentication Service only has one public static field. As long as the field is not used, variable initializer wouldn't get executed and no initialization takes place. Since static intiailizer only gets to execute once so only a single instance is created for the class. All the other requests would get the same instance.

Inner Holder Instance Class
This implementation would be useful in situations when the class has other properties as well. Based on the way static members are initialized in C#, access to any of the static members would initialize all of them. We might not want it for the singleton. This would certainly not be the case generally as we don't have other public static members for a singleton quite often. I think this implementation came from other languages where static members were initialized differently so in order to make sure that the member get initialized only when we desire it, they came up with this implementation.

Here since the inner class has the static member which would be initialized for singularity, only access to Instance property would lead to initialization of the singleton instance.

Please note that for any implementation using static fields, thread safety is ensured by the runtime creating only one instance of singleton type.

Lazy Singleton Instance:
In this approach, singleton instance is not created until one is requested. Once an instance is created for the particular singleton type, the same instance would be used for all the other requests for instances for the same type.

This is the most common implementation of implementation I have seen. In this approach, all the constructors of the type has private access. The class is sealed for inheritance for additional safety. And it has an static property, named Instance, with the same type. The property getter returns the same instance of the type for all the requests. It maintains a static variable for the same type and it just checks if the variable already has an object referred, if so, it just returns it, otherwise, it creates one and returns it.

The problem with this approach is that it is not thread safe. Two threads can enter the getter simultaneously. Both threads would pass the if statement and creates two different objects. Obviously the last instantiation would be used for future requests, but the other thread would use a different instance and the class obviously is not singleton anymore if it is resulting in creating more than one instance.

Synchronization Locks for Lazily Initialized Singleton:
The example presented for eager initialization just had the problem that it is not safe for multi-threaded access. So the natural solution comes to our mind, use some sort of synchronization block. Let's change the code like this:

The above code would cause the serialized execution of the getter block. Until one thread gets out of the block, the other thread can't enter. This would definitely ensure that only one thread is able to initialize it and no more than one instance of the singleton class are created. But there is a problem, this would always cause serialized execution and the singleton would be a performance bottleneck for a multi-threaded environment. After the instance is created, we don't want it to be synchronized. Let's update the code as follows and see if this would work:

This seems to ensure that once an instance is created, there is no synchronized access allowing more than one threads to pass through the getter without waiting for each others. Inside the if statement, it has a sync block. If an instance hasn't been created yet then it would make sure that only one thread goes through the block. Pretty!!! But there is a problem what if no instance has been created yet and two or more threads use the getter. They pass through the if statement successfully. Now only one thread enters the sync block, and then the others one by one. All causing a new instance to be created. This, again, breaks the singleton instance requirement as there are more than one instances.

In order to resolve the above problem, Double Checked Locking is used. There is one lock and two checks, hence the name. Inside the synchronization block, this would make sure that no instance is created by the other threads, waiting for their turn, to enter the block by introducing another if statement. This is for the thread which are already passed the first if statement and waiting for the lock. The other threads which enter the getter section after an instance is created wouldn't even be let in. Let's look at this:

.Net 4.0 Lazy<T>
We resorted to introduce sync locks because we thought this is our problem of providing thread safe access for singleton instance. As the old saying says, Avoid locks as much as possible in your code. Instead, try to transfer the responsibility to some other library which is already thread safe and people have invested so much in order to keep it like that. This would minimize the various deadlock and other performance bottleneck situations in your code.

In the below code, we have used one of the technique presented in Parallel Programming with Microsoft .net. Here we are delegating the responsibility of thread safety to Lazy<T> construct. This would also ensure the lazy initialization of the singleton instance. There is no problem that we are instantiating it in the initialization section as this would not initialize it until Value is first accessed. After the first time, this would always return the same instance. This is also very simple to understand, hence better readability. We are not using any synchronization constructs, yet the code has thread safety, Zindabad!!!


Monostate Pattern:
The whole purpose of Singleton is singularity. Monostate pattern is another way to achieve singularity without its structural constraints. Monostate doesn't require single instance constraint. There can be as many instances as you want but all would share their state hence showing behavioral singularity behavior. For monostate, the singular nature is transparent to the user of the type and supports polymorphic derivatives. You can see some comparison here: comparison between singleton and monostate pattern.

Issues with Singleton
We can certainly find a lot of references where Singleton is discussed rather mercilessly. People claim it's an antipattern rather others have called it evil. Those references definitely have a point and we must consider the singleton usage [both when to use it and the particular approach to singleton].

The way we implement singleton has a number of issues. It leads to a rigid, fragile and immobile design by bringing high level of coupling in our code [DIP]. It's against the agreed upon Dependency Inversion Principle which states:

HIGH LEVEL MODULES SHOULD NOT DEPEND UPON LOW LEVEL MODULES. BOTH SHOULD DEPEND UPON ABSTRACTIONS.

The implementation would cause other high level modules to depend on it, which is certainly not recommended. One of the biggest issue is that we would need to make compromises with unit testability of the singleton clients as singletons cannot be mocked or stubbed.

Singletons & Reflection:
Keeping constructor private, Singleton stops the otherwise instantiation of the type. In actual, this can be hacked. We can simply use reflection to create an instance of a type with private constructor as follows:

This can be used as follows for instantiating Authentication Service:

Unit Tests & Singleton:
Let's introduce the following method to AuthenticationService.

Now introduce a ShiftManager to our CoffeeHouseApp application.

It is impossible to test Login with this code as we cannot really mock the singleton class. But we cannot leave our code like this. This would then become a LEGACY CODE which is the code without any unit tests.

The virtual method would allow us to provide alternate implementation through overriding. We just need to create partial mock of ShiftManager and provide expectation for the method. This would make it easier for us to test Login method without worrying about Singleton. We can write the test for ShiftManager as follows:

Please refer this to incorporate NUnit with Visual Studio 2010. You can see the tests passing:


Singletons & Inversion of Control [IoC]:
The problem with singleton is both for its concept and implementation. Conceptually, the issue with singleton is its shared state. It's like a dignified Global Variable. Dignified, because it came from Gang of Four. If we have no issues with the concept then we don't need to use the same implementation as in the formal texts. We need a repository which could provide the same instance over and over whenever it is requested for an instance for a particular type. So a particular type might be a singleton in one application and not in others. IoC containers have made our lives easier in dealing with singletons. We can specify which type resolution should be singleton and rest is taken care of by the container. There are many IoC containers available in the market. Unity seems to have the greatest industry penetration [Mark Seemann - Dependency Injection in .Net].

Unity provides the support using Life Time Managers. While doing the type registration, we can specify how much we want the same instance to be shared. For registering a type to be shared for the lifetime of container, we use ContainerControlledLifeTimeManager

Download



References
Implementing Singletons: http://msdn.microsoft.com/en-us/library/ff650316.aspx
Double Checked Locking: http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
Judith Bishop, C# 3.0 Design Patterns [Chapter 5]: http://msdn.microsoft.com/en-us/library/orm-9780596527730-01-05.aspx
Singleton Vs Static Class : http://www.iridescence.no/post/SingletonvsStaticClass.aspx

Monday, July 16, 2012

Introducing Value Objects - Functional Programming

In the previous post, we introduced Value Objects. It would be interesting to see how we can introduce such types in C#. In this post, we will be implementing a simple value object based type. This would be an immutable one as the famous saying, "Value Objects should be immutable".

In .net framework, string is a reference type but mostly it behaves like a value type. It is an example of a value object implemented as reference type. When we think about this then we immediately question why in the world it was implemented as such. Why didn't Microsoft introduced string as struct. Or generally speaking, should we be using struct or class when defining such types in C#? Well, fortunately we are not the first ones in the world who have questioned that. Please refer this discussion why it makes more sense to be implementing types for our value objects as reference types. It is better for convenience, performance and usability concerns.

Let's first introduce a simple immutable type in C#, named Barista. A barista is identified by Id. It also has a first and last name. Since this type is immutable, its members cannot be modified after constructor finishes execution. There is only one constructor which expects Id and names. After verification of arguments, it assigns them to its local members.

We will also need to override these methods so that equality checks are structural checks where member's values are checked for equality instead of their references.

Additionally we can also override equality (==) and non-equality operators as follows:

This seems logically true but it is not. Running this would show us the surprise. Basically we are causing non-limiting recursive calls between equality and non-equality operators and Equals method. This is causing the StackOverflow exception.

Let's try updating the equality by taking little advice from Microsoft.

Now we can use the code without any further exceptions!!!

Zindabad!!!

Sunday, July 15, 2012

Design Guidelines: Purely Functional Data Structures

In the previous post, we discussed how we can use private static to make our methods more aligned to the idea of pure functions. Since they don't allow to use instance level data, they provide better multithreading support by avoiding any possible side effect. Hence we don't need any synchronization block to serialize the execution flow for multiple threads. It's not like that we should always be creating our private methods as static but we should definitely be thinking about it. Obviously there are situations when we need instance context.

One such example would be to raise any instance-level event [Remember sender in event args]. Unless we pass the instance itself (this) to the method, this doesn't seem possible. Doing that, again, we are opening ourselves to side effects. Based on this discussion, I think that a better thoughtful combination of static and instance-level private methods should be carefully defined for any design. But following the exercise as followed in the last post should help us limiting them. This combination would also ensure that we keep the length of our private methods to the minimum. Their role can be defined as minimum wage labors hired for the little chores. It doesn't seem appropriate to put the heavy loads on their shoulders. We need to define exactly how they would coordinate their work. We just can't put the responsibility of all labors to one of them and expect harmony. You might have seen people asking about how to test private methods and there are ways to do that (accessors in MSTest). They are great to think about testable heavy logic but the beginning is wrong, this heavy logic doesn't deserve to be there.

Terminologies:
Object immutability allows safe sharing of objects [Florian Leu & Microsoft Research]. Real immutable objects require no synchronization mechanism (locking) and are thread safe. Microsoft P & P defines the purely functional data structures as follows:

A data structure that can only be accessed by pure functions. An instance of immutable type. [Parallel Programming with Microsoft .net - Design Patterns for Decomposition and Coordination on Multicore architectures]

The same book defines immutable data as the data that cannot be modified after it's created while the immutable types are those types whose instances are immutable. On the contrary, mutable data is the data which can be modified afters it's created and the the types whose instances are mutable are called mutable types.

[Brian Goetz] has an amazing article on Developer Works discussing the benefits of Immutable data structures. It's a really old post, and obviously, it discusses in the context of java but a really interesting read. On the Microsoft front Eric Lippert has discussed this.

readonly Collections & ReadOnlyCollection
Turning a type immutable means that the members are marked readonly. As we know that a readonly member cannot be modified after the constructor code finishes execution. After that we cannot change the value of a member of value type. We also can't change the object referenced by reference type member, whether it is a scalar object or a collection. Yes, for collection based members, it would be guaranteed that the same collection would be used throughout the lifetime of the immutable type but there is no guarantee that it would continue to hold the same items. A collection based member of an immutable type can add / remove member without any issue with the sanctity of immutable behavior.

Let's assume that in order to attract more customers, our coffee house is adding the functionality to introduce discount offers. We can introduce a DiscountOffer type as follows:

This seems to be a perfectly good immutable type with its members specified as readonly. This type would be shared by all the consumers of this type. They can see if this offer is for only members. They can show the title of the offer including the details about the duration of the offer. Additionally, they can see what products are included for this offer. Here is the catch, the collection object is non-modifiable but any consumer can add / remove members from the collection which would be weird for a discount offer. Once introduced, we don't want any client to be updating any part of the offer.

Where the constructor of the type can be updated as follows:

Since the products list is a reference type so any updates in the list would reflect in the OfferProducts member. If you don't want that then you can create a deep copy of the list before assigning it to the ReadOnlyCollection member.

Popsicle Immutability [Immutable after freezing]
These are data structures which are modifiable when they are created. They can be turned non-modifiable. In order to turn them so these types provide a special operation. They result in better performance once turned non-modifiable.

WPF has a number of freezable concepts including brushes, pens, transformations, geometries, and animations. Most of them seem to be part of graphics sub-system. The freezing part of freezable types is interesting. Let me make it easier for you by stating the following:

"All freezable objects cannot be frozen all the time. We must check if it can be frozen before causing it to freeze."

Some part of our code is in the middle of updating the object's properties when some other part of the code wants it to be frozen. We might have it data bound to some UI control. If we freeze it then it wouldn't be able to reflect updates from user interaction with UI resulting in exception situation. WPF has resolved this issue by providing CanFreeze property. In WPF, Freezable(s) keep raising Changed event whenever their state is changed. Once frozen, there is no need to subscribe to that event as the object wouldn't be changing its state afterwards.

Objects of this type are thread safe after they are frozen. For our custom popsically immutable types, we must make sure that the objects are safely shared across different threads. WPF Type System has made this easier for us. Freezable is a DispatcherObject. So, it has an associated Dispatcher until it is frozen. Attempting to access it from a different thread would result in an exception. But if we freeze it, it disassociates itself from the Dispatcher by setting it null. Now it can be shared across threads without worrying about updates in its state.


Like Clone() method from ICloneable interface, types should be clearly documenting the expectations of Freeze() method. In ICloneable case, it might return a deep copy or a shallow copy of the object. We always have to see type's documentation for the expected behavior. This is actually an issue with polymorphism which is taken care of by good documentation. For your types, you can also freeze the object deeply or otherwise but it should be clearly documented. WPF keeps it deeply frozen. That is why it has a CanFreeze property which checks even if any of the sub-object is being used then it cannot be frozen.

You might want to name your method differently (e.g. TurnImmutable()) for your type but the concept should be same. In WPF case, it frees itself from the dispatcher bounds (sets the property to null). In your case, you might want to avoid using synchronization blocks once this turns immutable. This means there wouldn't be any serialized thread access for the instances hence lesser waits for threads and hence it can cause better performance of your applications.

Let's introduce a new type for the purpose of introducing this concept to our project. It's sub-types would be Popsically immutable [I know there is no word like popsically (here I get advantage of being non-native :))]

This type is different than WPF's Freezable on a number of different account. Let's discuss why we are introducing it differently than that.
  • Calling TurnImmutable() method checks if the object is already turned immutable, if so then an InvalidOperationException is thrown. On the contrary, Freezable.Freeze() just swallows the call. This seems like a deception. If a function is not able to perform its duty, then it should throw exception. The caller must check if it is already frozen / immutable before attempting to turn it so.

  • CanBeTurnedImmutable is equivalent to Freezable.CanFreeze property. First of all, why we have introduced this as a method instead of a property. Basically this is following Microsoft's recommendation of defining properties. Since the method uses CanBeTurnedImmutableCore virtual method. It can be overridden by a child class and might be expensive operation.

  • Both Freezable.Freeze() and Freezable.CanFreeze use Freezable.FreezeCore() with a flag parameter [isChecking] to identify if this call is just for checking purpose or actually turning the instance immutable. This flag based approach to drive method behavior should be avoided. This clearly means that the method has more than single responsibility which is never recommended. We have avoided using it like that.
This implementation also has some limitations. They are as follows:
  • This does not support change notification. Freezable supports change notifications through events. It would continue to raise the events until the object turns unmodifiable. After that there cannot be any such event possible. Since this is not a necessary condition for immutability, let's leave that here. You can provide the event if you need so.

  • The type is not thread safe. What!!! Don't shoot me for that. Let's do it brute force.

  • Where _lockObj can simply be as follows:

You might argue if we really need a lock statement in CanBeTurnedImmutable() method. But, avoiding that, you can easily turn yourself into situation when a thread is in the middle of the execution [after having passed the if statement]. During this time, another thread causes the execution of TurnImmutable() method. The first thread obviously get true from the method but when it calls the TurnImmutable() it is slapped with an exception.

There might be other cases when multi-threaded execution takes place as follows:

After the first thread passes the if statement and it hasn't entered TurnImmutable() call yet. The other thread enters and also passes through the if statement. They both call TurnImmutable(). One thread would be successful while the other would get the exception. Now when you see this you might realize while Freezable swallows the call in this case. Well, this is a trade-off. Make your decision based on your requirements. But you should understand the gains and pains of both approaches.

Here we have introduced the ...Core() methods as virtual. You might want to turn them into abstract methods.

In order to turn your data structures into a popsically immutable data structure, you would need to inherit from the type defined above. You would need to provide definition of virtual / abstract methods. You would also need to check all the attempts to modify the object and throw an exception if the object has been turned immutable already.

Observational Immutability
This is the type of immutability where object is immutable for the outside. All the public fields and properties cannot be set using type's instance. They can only be modified from within. Basically the setter for the property is not public. It can be private or protected based on the placement of class in the inheritence hierarchy (if there is any).

Observational immutability reduces the possibilities of updating the state of object. Now they can only be updated by the outside world using public behaviors (methods) of the object. In our Coffee App example, we can introduce the features to have the details about customers. We can assign a CoffeeCard to a customer. If a new card is assigned to a customer then the previous card just gets overridden.

In this example, the setter for Card is kept private so it cannot be updated by the consumer of the object of type Customer. But from within the class, it can get overridden. It's not necessary that only object's interfaces (public methods) cause it to be updated. It can also be updated by any other event from some other object that the Customer has subscription. But it is to make sure that all these updates are caused from within the definition of the type itself.

You might argue if this should even be called as immutable as the object can clearly update its state after being created.

It must be remembered that Observationally immutable types are not thread safe if there is no special synchronization measures taken for thread safety. Two threads might enter AssignCard method. Now the final value of card would depend on which one of the thread assigns it last. Also the "Other special things" would depend on the Card at the instance when the statement is being executed.


Immutable Objects are Value Objects
As Martin Fowler suggests, Value Objects are objects that follow value semantics instead of reference semantics. Two such objects are equal if all of their fields are equal.Immutable types can also be implemented as value objects. They seem to allow manipulation of object but every manipulation result in a new object. One such example is string based objects. string seem to allow manipulations but any such manipulation result in created of a new string object. The same is true for all Value Objects.

Value Objects support structural equality. Two value objects are equal if all their members are equal. In C#, value objects are also defined using classes. That is why we need to provide overloads of equality operator i.e. == and Equals method to work on checking equality based on the member's values. This is because the identity of an immutable type is its state and not its reference e.g. if firstInteger and secondInteger are both assigned the value "2", then they are equal. On the other hand reference objects are only equal if they refer to the object created using the same new operator with no consideration whatsoever about the state of its members.

Value Objects are also side effect free types. Hence they are the ideal candidates for functional and multi-threaded code.

An interesting read about value objects: Values in Object Systems.

Basically people have a lot of confusion when they are first learning the object oriented language because of context specific terminologies. So the value / reference types and passing by reference and value are different context specific terminologies.

"It is possible to pass a value type object by reference and vice versa. "

The examples of passing by value and by reference in WPF are StaticResourceExtension and DynamicResourceExtension. StaticResourceExtension uses resource as passed by value that is why when the other reference starts using some other resource, this still keep referencing to the older object. On the contrary, DynamicResourceExtension uses them by reference, so if the reference gets updated to refer to a new object, the extension start using the newer instance. Here I have deliberately used "reference REFER", using "reference points" gets the same picture of reference in our mind as being a pointer which creates dirty desires to use it like one which is not possible. Abstinence is the key :) [See Erik Lippert]