Saturday, January 23, 2010

Implementing Dispose pattern and Destructor in C#

namespace VariousExperiments.disposabl
{
public class GrandParent : System.Object, IDisposable
{
public unsafe IntPtr? pointer;
public unsafe IntPtr? stringPointer;
public List someItems=new List();

// Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be disposed.
public virtual void Dispose(bool disposing) {
if (disposing) {
//Dispose the managed resources by calling dispose on them
someItems.GetEnumerator().Dispose();
//Suppress finalize since Dispose is called.
//No need to ask the runtime to call the finalizer over this object
GC.SuppressFinalize(this);
}

//release managed resources
someItems = null;
//Release Unmanaged resources
unsafe
{
pointer = null;
stringPointer = null;
}
}
#region IDisposable Members

public void Dispose()
{
Dispose(true);
}

#endregion

// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
~GrandParent() {
Dispose(false);
}

}

public class Parent : GrandParent
{

public override void Dispose(bool disposing)
{
//Release extra resources, if any
base.Dispose(disposing);
}
}

public class Child : Parent {

public override void Dispose(bool disposing)
{
//Release extra resources, if any
base.Dispose(disposing);
}
}
}


--One more time.

We "need" destructor and/or dispose when we have references to unmanaged resources in our object. Since GC knows how to kill (and recollect memory) managed references, it is fine as long as an object doesn't has any unmanaged resource references in it.

Monday, January 18, 2010

Deep copy an object in C#d

A common utility code to DeepClone a given object.
The constraint is that class must implement SerializableAttribute.

public static T DeepCopy(T obj) where T:class
{
T result = null;

using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;

result = (T)formatter.Deserialize(ms);
ms.Close();
}

return result;
}

Sunday, January 10, 2010

calling virtual method within a constructor.

Rules-
1) Virtual method is called over the most derived object, method table is used for the most derived object.
2) Constructor is called from base to derived type.

Considering these rules, calling a virtual method inside a constuctor is unsafe for two reasons (what i can think of right now).

1. Instance may not be completely initialised for the object.
Sample Code:
class Parent
{
public Parent()
{
DoSomething();
}
protected virtual void DoSomething() {};
}

class Child : Parent
{
private string foo;
public Child() { foo = "HELLO"; }
protected override void DoSomething()
{
Console.WriteLine(foo.ToLower());
}
}

This code results in NullReference exception, since virtual method is called for the most derived type, and in this case the most derived is not completely initialised at the time virtual method is called.

2. The behaviour of the virtual method called would vary if (in future) a new class is introduced in the inheritance hierarchy.

Also, resharper shows a warning if we call a virtual method from inside a constructor. This warning would be suppressed if the type making a call to virtual method is sealed or if the method is marked as "sealed override" (then we won;t be having Risk-2).

Saturday, January 9, 2010

MVC - Beginner

To Confuse more... It is separation of UI with business logic and underlying object. The View captures user events and passes it on to Controller. The controller accepts events from view and passes it on to Model. The model exposes behaviour and activities to Controller, and returns appropriate result to controller. Controller takes result from Model and signals (updates) view accordingly.

To my best of understanding (so far). Each of these entities interact with each other on contract (interface) bases. View has the handle of desired controller, and on each user event that view exposes it knows the corresponding method/event to invoke of the controller.

Controller has handle of View and Model. On each event/method being exposed it signals the model about user activity. Controller knows nothing about the state of Model, it just passes the user event and input (got from view) to Model. Model maintains its internal state, and as per event and user event may choose to update its state. The state that Model choose to expose to user is exposed through some contract (or may be directly to controller). On invoking some method of model, controller sends the state back to View, which is then shown to the user.

Phew... i hope my understanding is correct. Will write more about it.