Nerdy tidbits from my life as a software engineer

Friday, November 21, 2008

Type Hinting With Dynamics (Wouldn’t That Be Nice?)

I’ve blogged a little bit before about one of the big problems I foresee with dynamics, being that you loose all strong typing by using them – even if you know ahead of time what methods you will be invoking on a dynamic type.  Of course this is the tradeoff you get for using dynamic types, but it seems like a smart idea to give developers a way to pseudo-strong-type something at compile time, even if the CLR is determining what gets invoked at runtime.

For instance, lets say I have a dynamically generated type that I want to invoke using a dynamic.  I might have a class with a property that lets a consumer of that class set the dynamic instance, like this:

public dynamic SomeDynamic
{
  get;
  set;
}

public void Whatever()
{
  this.SomeDynamic.DoSomething();
}

It doesn’t matter what type SomeDynamic is.  Maybe it’s some COM object; maybe it just an arbitrary C# object.  Who cares.  But if I’m expecting that, whatever type SomeDynamic is, it has a method called DoSomething that takes no arguments, it would really be nice if I could somehow declare that expectation into my code explicitly.  That way I could (potentially) avoid runtime errors when people set SomeDyanamic to be an object that doesn’t define a method called DoSomething.  And, perhaps even more importantly, I can help myself by allowing intellisense to suggest methods and arguments for me after I type “.”.  This way, if I compile:

public void Whatever()
{
this.SomeDynamic.DoesNotExist(bogusArg1, bogusArg2); }

I can get a warning that lets me fix the problem ahead of time.  The way I envision this working is by changing the dynamic’s declaration to something like this:

public dynamic<ISomeInterface> SomeDynamic
{
  get;
  set;
}

…or maybe even…

public [TypeHint(typeof(ISomeInterface))] dynamic SomeDynamic
{
  get;
  set;
}

It seems awfully sad to me that I will loose the ability to catch things as trivial as spelling errors until I run my code.  They do happen, after all, especially without the help of intellisense.  Wouldn’t it be nice if we could check for them before-hand?

0 comments: