Crucial RealSSD Tested

March 26, 2010

Some not-so-good news for the SSD drive I was keeping my eye on: http://www.anandtech.com/storage/showdoc.aspx?i=3779. Their drive died after some use and there’s some very serious performance problems after enough data has been written to the device.  Here’s hoping Crucial fixes the problem and AnandTech testing that all is well…

Advertisements

Dynamic C#

March 21, 2010

So I installed VS2010 RC and am reading some books… and came across a demo of the new “dynamic” type in C# 4.0 that I thought I’d share …

The Basics

[TestMethod()]
public void BasicDynamicTest()
{
    dynamic f = Activator.CreateInstance(Type.GetType("System.Text.StringBuilder"));
    f.Append("Hello");
    f.Append(" World!");
    Assert.AreEqual("Hello World!", f.ToString());
}

The type of f is is determined at runtime.  You might be wondering why you’d want to do something like the above.  You might start thinking about evaluating expressions at runtime, a la scripting or dynamic languages like Python or Ruby.  How about something even more clever, like defining the structure of an object at runtime?

DynamicObject

To do so, you need to create a class that inherits from the DynamicObject class and then you can do things like override the TryGetMember method so you can create your own methods on the class at runtime:

// First, make sure MyXML inherits from DynamicObject
class MyXML : DynamicObject
{
	private XDocument _xml = new XDocument();

	// Simple constructor
	public MyXML(string x)
	{
		this._xml = XDocument.Parse(x);
	}

	// Let's dynamically create our own methods
	public override bool TryGetMember(GetMemberBinder binder, out object result)
	{
		string nodeName = binder.Name;
		result = _xml.Element("top").Element(nodeName).Value;
		return true;
	}
}

[TestMethod()]
public void MyXMLConstructorTest()
{
	dynamic xml = new MyXML(@"
		<top>
			<node1>Alpha</node1>
			<node2>Beta</node2>
		</top>");
	Assert.AreEqual("Alpha", xml.node1);
	Assert.AreEqual("Beta", xml.node2);
}

Drawbacks?

While you can basically do this with Reflection, dynamic code is much easier to deal with. You lose Intellisense on dynamic types, compile-time checking, and performance. The DLR (Dynamic Language Runtime) does the runtime interpreting for you. As the author of the book that I’m reading states, you generally wouldn’t want to use dynamic code except where you’d otherwise be using reflection; C# by nature is statically-typed so most of the time, you’re better served by writing static code.

Incidentally, the C#/.NET 4.0 book I’m reading (1 of 3) is Introducing .NET 4.0 With Visual Studio 2010 by Alex Mackey. I haven’t gotten through enough of it to have a firm opinion but I picked it up because I liked the sharp and tight focus on things that are new in 4.0 as well as the focus on MVC 2 and jQuery (there looks to be some nice interop there).