Sponsored By Aspose - File Format APIs for .NET

Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more!

C# Feature I would love — Dynamic Types w/ Interfaces

Today I realized I wanted a feature in C#, but it was not there.

Imagine you have the code below

public class Foo{
  public void Bar(){
    var fieldValue = new {
                          ParentKey = "something",
                          SectionKey = "section",
                          FieldKey = "field",
                          LabelKey = "label"
                        } : IFieldValue;

public interface IFieldInfo : IFieldValue
    string ParentKey { get; set; }
    string SectionKey { get; set; }
    string FieldKey { get; set; }
    string LabelKey { get; set; }

Here is what I was trying to accomplish. I have a method which accepts the interface IFieldValue but in my code scope I do not have an instance of anything which implements IFieldValue. Sure I could new up a new instance of something which implements IFieldValue but this is an issue for a few reasons, mostly because anything that currently implements IFieldValue is pretty heavy weight. Sure I could create a very small class that only implements IFieldValue (actually what I did to solve my problem) but why should I have to go through the ceremony of creating a class which only implements an interface since C# offers dynamic types?

Now I am sure there are a dozen reasons why this is a stupid idea, but if this was in the language today I would have been a happy camper and the number of lines code I would have had to write would have been reduced.

** Edit **
Mark Rendle @markrendle pointed me to the Impromptu-interface project on github which attempts to solve this problem. I would still like to see something like this baked into the language, but this would work as well for now
** End Edit **

Till next time,

This entry was posted in Uncategorized and tagged . Bookmark the permalink. Follow any comments here with the RSS feed for this post.

Comments are closed.