1

I've read a number of articles including this one on the subject of Empty or 'marker' interfaces. I have concluded that I cannot use custom attributes in my case as I need to be able to include the instance of a class to another method and, as these classes have nothing in common, I have no option but to use a 'marker' interface.

As an example, I might have

public class Foo
{
    public int Id {get;set;}
    public string Name {get;set;}
}

public class Bar
{
    public Guid Identifier {get;set;}
    public DateTime DueDate {get;set;}
}

and I need to pass them to a method in another class and because there may be many different types that need to be passed to the method, I've defined it like this...

public void MyMethod(IMyInterface model)
{
    // Do something clever here
}

And All I've had to do to make this work is to 'implement' IMyInterface on Foo and Bar.

So to the question. I now find I need to call my MyMethod() method with an anonymous type created from a LINQ statement, so I tried this ...

var data = <Some Complex LINQ>.Select(a=> new { AString = a.Value1, ADecimal = a.Value2});
MyClass.MyMethod(data);

Sadly, I get the following compile-time error:

Error 202 Cannot convert type 'AnonymousType#1' to 'IMyInterface' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

Now, I know I could create a local class and use that in the same way as I have my standard classes, but my requirements mean that I'm going to have a lot of these LINQ queries in my up-coming set of work so, if possible, I'd like to find a solution that allows me to use Anonymous Types.

Does anyone know of a solution or workaround for the error I'm getting?

4
  • 2
    may be many different types that need to be passed to the method then use object instead of the marker interface. I see no value in using a marker interface at this point Commented May 6, 2015 at 11:33
  • Doh. Let me go and try that. Commented May 6, 2015 at 11:35
  • @Jehof, if you add that as an answer, I'll accept it. Commented May 6, 2015 at 12:38
  • @Jehof is right. you're trying to pass a generic class to a method that's supposed to receive an interface. Commented May 6, 2015 at 15:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.