views:

274

answers:

9

I have a concrete class that contains a collection of another concrete class. I would like to expose both classes via interfaces, but I am having trouble figuring out how I can expose the Collection<ConcreteType> member as a Collection<Interface> member.

I am currently using .NET 2.0

The code below results in a compiler error: Cannot implicitly convert type 'System.Collections.ObjectModel.Collection<Nail>' to 'System.Collections.ObjectModel.Collection<INail>'

The commented attempt to cast give this compiler error: Cannot convert type 'System.Collections.ObjectModel.Collection<Nail>' to 'System.Collections.ObjectModel.Collection<INail>' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion.

Is there any way to expose the collection of concrete types as a collection of interfaces or do I need to create a new collection in the getter method of the interface?

using System.Collections.ObjectModel;

public interface IBucket
{
    Collection<INail> Nails
    {
        get;
    }
}

public interface INail
{
}

internal sealed class Nail : INail
{
}

internal sealed class Bucket : IBucket
{
    private Collection<Nail> nails;

    Collection<INail> IBucket.Nails
    {
        get
        {
            //return (nails as Collection<INail>);
            return nails;
        }
    }

    public Bucket()
    {
        this.nails = new Collection<Nail>();
    }
}
+6  A: 

C# 3.0 generics are invariant. You can't do that without creating a new object. C# 4.0 introduces safe covariance/contravariance which won't change anything about read/write collections (your case) anyway.

Mehrdad Afshari
A: 

It's the age-old issue that C# 3.0 and down doesn't support co-variance; you need to cast nails to INail for it to compile. C# 4.0 will address this.

STW
Casting nails to Collection<INail> doesn't compile. I mentioned this in the original question.
jameswelle
You mention boxing, not Casting (see my answer for the difference in this case)
johnc
Are you saying that the (nails as Collection<INail>) is a boxing operation, not a casting operation?http://msdn.microsoft.com/en-us/library/cscsdfbt%28VS.71%29.aspx
jameswelle
It is my understanding that boxing occurs on value types, which are not used here.
jameswelle
Unless I am wrong about Collection<T> (as I said I can't test here) there should be an implicit Cast<T> function on the collection. There certainly is on a List<T>
johnc
Sorry, I didn't mean 'implicit' in the keyword sense of the word, just that you can call it implicitly
johnc
See the answer here http://stackoverflow.com/questions/53395/suggestions-wanted-with-lists-or-enumerators-of-t-when-inheriting-from-generic-cl
johnc
I am on .Net 2.0 as well so I am out of luck there too.
jameswelle
Ah, snap. It looks as if you might just have to brute force a loop
johnc
+6  A: 

Just define nails as

Collection<INail>
ChaosPandion
It is a solution but if you want a collection of Nail object only, it is a problem because every object implementing INail could be added in the collection.
Francis B.
I would live with this until C#4. Of course this is up to the original poster.
ChaosPandion
I should have mentioned that these classes are serialized using the XmlSerializer, which is why the collection has to be defined as Collection<Nail> and not Collection<INail>.
jameswelle
+1  A: 

Why not just return it as an interface, just have all your public methods in the interface, that way you don't have this problem, and, if you later decide to return another type of Nail class then it would work fine.

James Black
A: 

What version of .Net are you using?

If you are using .net 3.0+, you can only achieve this by using System.Linq.

Check out this question, which solved it for me.

daub815
I am using .Net 2.0
jameswelle
A: 

you could use the Cast extension

nails.Cast<INail>()

I can't test it here to provide a more comprehensive example, as we are using .NET 2.0 at work (gripe gripe), but I did have a similar question here

johnc
A: 

There is one solution that might not be quite what you are asking for but could be an acceptable alternative -- use arrays instead.

internal sealed class Bucket : IBucket
{
    private Nail[] nails;

    INail[] IBucket.Nails
    {
        get { return this.nails; }
    }

    public Bucket()
    {
        this.nails = new Nail[100];
    }
}

(If you end up doing something like this, keep in mind this Framework Design Guidelines note: generally arrays shouldn't be exposed as properties, since they are typically copied before being returned to the caller and copying is an expensive operation to do inside an innocent property get.)

bobbymcr
A: 

use this as the body of your property getter:

List<INail> tempNails = new List<INail>();
foreach (Nail nail in nails)
{
    tempNails.Add(nail);
}
ReadOnlyCollection<INail> readOnlyTempNails = new ReadOnlyCollection<INail>(tempNails);
return readOnlyTempNails;

That is a tad bit of a hacky solution but it does what you want.

Edited to return a ReadOnlyCollection. Make sure to update your types in IBucket and Bucket.

RCIX
I think this is what I will have to do, but I will return a ReadOnlyCollection since adding to the returned collection won't affect the original.
jameswelle
There, fixed.
RCIX
A: 

C# doesn't support generic collections covariance (it's only supported for arrays). I use an adapter class in such cases. It just redirects all calls to the actual collection, converting values to the required type (doesn't require copying all list values to the new collection). Usage looks like this:

Collection<INail> IBucket.Nails
{
    get
    {
        return new ListAdapter<Nail, INail>(nails);
    }
}

    // my implementation (it's incomplete)
    public class ListAdapter<T_Src, T_Dst> : IList<T_Dst>
{
 public ListAdapter(IList<T_Src> val)
 {
  _vals = val;
 }

 IList<T_Src> _vals;

 protected static T_Src ConvertToSrc(T_Dst val)
 {
  return (T_Src)((object)val);
 }

 protected static T_Dst ConvertToDst(T_Src val)
 {
  return (T_Dst)((object)val);
 }

 public void Add(T_Dst item)
 {
  T_Src val = ConvertToSrc(item);
  _vals.Add(val);
 }

 public void Clear()
 {
  _vals.Clear();
 }

 public bool Contains(T_Dst item)
 {
  return _vals.Contains(ConvertToSrc(item));
 }

 public void CopyTo(T_Dst[] array, int arrayIndex)
 {
  throw new NotImplementedException();
 }

 public int Count
 {
  get { return _vals.Count; }
 }

 public bool IsReadOnly
 {
  get { return _vals.IsReadOnly; }
 }

 public bool Remove(T_Dst item)
 {
  return _vals.Remove(ConvertToSrc(item));
 }

 public IEnumerator<T_Dst> GetEnumerator()
 {
  foreach (T_Src cur in _vals)
   yield return ConvertToDst(cur);
 }

 IEnumerator IEnumerable.GetEnumerator()
 {
  return this.GetEnumerator();
 }

 public override string ToString()
 {
  return string.Format("Count = {0}", _vals.Count);
 }

 public int IndexOf(T_Dst item)
 {
  return _vals.IndexOf(ConvertToSrc(item));
 }

 public void Insert(int index, T_Dst item)
 {
  throw new NotImplementedException();
 }

 public void RemoveAt(int index)
 {
  throw new NotImplementedException();
 }

 public T_Dst this[int index]
 {
  get { return ConvertToDst(_vals[index]); }
  set { _vals[index] = ConvertToSrc(value); }
 }
}
skevar7
That kind of looks like overkill at this point....
RCIX
It's overkill if you only need it once, but this class makes life easier when you need covariance more oftenly.
skevar7
Cool, I think this is exactly what I need!
jameswelle