Carl’s Geek Notes

June 20, 2007

ICloneable tricks & shortcuts

Filed under: C#/.NET, Computers, Programming — Carl @ 1:08 pm

Here’s a couple of tricks to implementing ICloneable.

First, if your class supports serialization or deserialization, you can serialize the object you wish to clone and deserialize it to a new object.  This has a couple of obvious drawbacks:

  • If you’ve marked fields or properties to be ignored by serialization, you won’t see them in the clone.
  • If you’ve implemented IXmlSerializable to make custom serialization, you’ll lose values that are not in the XML.

Another trick that I’ve come up with is to use Reflection to clone:

public static object CloneThroughReflection(object source)
{
Type ObjectType = source.GetType();

// Create a new object of the same type as the source and call its default constructor
object MyClone = System.Activator.CreateInstance(ObjectType, null);

// Loop through the fields
FieldInfo[] FieldInformation = ObjectType.GetFields();
for (int i = 0; i < FieldInformation.Length; i++)
{
// Set the clone's field to the same value as the source's
FieldInfo MyField = FieldInformation[i];
object SourceValue = MyField.GetValue(source);
MyField.SetValue(MyClone, SourceValue);
}
return MyClone;
}

This function is more accurate at making a deep clone of an object, as it doesn’t rely on a field’s or property’s inclusion in the XML to appear in the clone.

June 1, 2007

LOLCODE

Filed under: Just for Fun, Programming — Carl @ 6:55 am

If you’re a programmer and you’ve not seen LOLCODE, it’s worth a visit–you’re guaranteed a chuckle out of it!  I think it’s destined to become the language of choice for script kiddies and 1337 haX0rs everywhere:

HAI
CAN HAS STDIO?
I HAS A VAR
IM IN YR LOOP
 UP VAR!!1
 VISIBLE VAR
 IZ VAR BIGGER THAN 10? KTHXBYE
IM OUTTA YR LOOP
KTHXBYE

Lots of amusing things, like BTW <comment> to write a comment, BRB to sleep the thread, and a lively discussion as to whether OMG or WTF should be the keyword to throw an exception.

KTHXBYE!

Blog at WordPress.com.