Saturday, May 7, 2011

Cloning objects in C# to achieve pseudo byval with ICloneable

I came across this little nugget recently and while the ability to do this has been around for quite some time in c# I found it to be very handy and wanted to share. If you have an object (class) in C# where you’d like to clone an entire reference object to another without transferring id/hash, basically achieving a by value transfer. The approach is to use the ICloneable interface on your class. Here is my base entity class which most all entity’s in my application inherit from.

public class EntityBase : IEntityBase, ICloneable
public Guid Id { get; set; }

public EntityBase()
Id = Guid.NewGuid();

public object Clone()
return MemberwiseClone();

Take note of the Clone() method, this is a required member of using ICloneable and it brings us to the usage for the object cloning.

MyObject origObj = querySomeRepo.FindOne<MyObject>(f => f.Id == Guid.Parse(id));
MyObject newObj = (MyObject)familyOrig.Clone();

That’s it and newObj is now a clone of the original retaining all property values without being the exact same object.


Debugging Visual Studio 2010 MVC or Silverlight Apps in non-default web browser

A while back I was constantly vexed by Visual Studio 2010′s apparent lack of non default browser support for debugging MVC and Silverlight applications. The problem is that I can’t stand for using any variant of IE as my default browser for reasons better suited for a different post. At face value VS has no way to accomplish this in it’s 2010 version for MVC or any non web-forms application, instead what one needs to do is “trick” the IDE, it’s a bit of a kludge but bear with me.

  1. First you need to create your MVC, Silverlight, etc project of your choice, if you have an existing project then move on to Step 2

  2. Next step is to create what I’ll term as a Dummy Debug project inside of your existing Solution, set the project’s type to ASP.NET Web Forms application, very important this must be a Web Forms project

  3. Once you have the web forms project create any aspx file in the root of the Dummy project, doesn’t matter what its named, you’ll need to right click on it and select the “Browse With” option once it’s created


  4. On the next dialog box simply select the browser of you choice and select “Set as Default”


  5. Close this dialog

You’re all set, now when you debug your MVC app it will launch in the browser you’ve selected and your systems default browser won’t be affected!