Interfaces and casting

W

wdudek

ok, a little background first. I have the following class

public class LineItemColleciton : IList<LineItem>
///implements the IList as well as other business logic

The class LineItem implements the interface ILineItem
public class LineItem : ILineItem

Then I have the interface IOrder

public Interface IOrder

IList<ILineItem> LineItems

is there a way for my class Order to "gracefully" implement this

public class Order


public LineItemColleciton LineItems { get; set;}

I'm doing this in 2.0.

My solution was to refactor the original property with a differnt name, but
was hoping I could somehow cast it?
 
J

Jesse Houwing

* wdudek wrote, On 10-9-2009 23:02:
ok, a little background first. I have the following class

public class LineItemColleciton : IList<LineItem>
///implements the IList as well as other business logic

The class LineItem implements the interface ILineItem
public class LineItem : ILineItem

Then I have the interface IOrder

public Interface IOrder

IList<ILineItem> LineItems

is there a way for my class Order to "gracefully" implement this

public class Order


public LineItemColleciton LineItems { get; set;}

I'm doing this in 2.0.

My solution was to refactor the original property with a differnt name, but
was hoping I could somehow cast it?

You could implement the original method explicitly and use that...

class Order : IOrder
{
#region IOrder Members
IList<ILineItem> IOrder.LineItems
{
get;
set;
}
#endregion

public LineItemsCollection LineItems
{
get
{
return (LineItemsCollection)((IOrder)this).LineItems;
}
set
{
((IOrder)this).LineItems = value;
}
}


}

class LineItem : ILineItem { }
public interface ILineItem { }
interface IOrder
{
IList<ILineItem> LineItems { get; set; }
}
public class LineItemsCollection : List<ILineItem>
{
}

Best seems to be to update the Interface :)

Any other solution will only work in the upcoming .NET 4.0 which solves
these funny cannot cast errors during compile time :)
 
W

wdudek

Thanks, I was pretty much afraid that was the answer. I am looking forward to
4.0 to see how I can do the same there though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top