0

I have the following class and interface:

public interface IFieldFiller
    {
        string Content { get; set; }
        Boolean Nullable { get; set; }
        string Name { get; set; }
    }

and

[DataContract]
public class FieldFiller : IFieldFiller
{
    [DataMember]
    public string Content { get; set; }

    [DataMember]
    public Boolean Nullable { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public StoredProcedure StoredProcedure { get; set; }

    [DataMember]
    public string NameSpace { get; set; }
}

I then use the following Linq statement to build a list of these objects:

Fields =  temp.merged_fields.Select(f => new FieldFiller { Name = f.name, NameSpace = f.@namespace, StoredProcedure = new StoredProcedure { Name = f.sproc1.name, Parameters = f.field_params.ToDictionary(p => p.sprocParam.name, p=>p.value)}}).ToList()

and I keep getting the following exception:

Error   1   Cannot implicitly convert type 'System.Collections.Generic.List<Services.Data.EmailTemplateAccess.Contracts.FieldFiller>' to 'System.Collections.Generic.List<Services.Data.EmailTemplateAccess.Contracts.IFieldFiller>'    

I don't understand why I am getting this error when FieldFiller implements IFieldFiller. I have already verified that they are in the correct namespaces. Any help would be appreciated.

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
Mike
  • 1,718
  • 3
  • 30
  • 58
  • `D : B` does not imply `List : List`. You need to add the `D` elements to `List` manually. – lukegravitt Aug 12 '13 at 23:31
  • According to that blog, wouldn't FieldFiller be smaller than IFieldFiller, making it a covariant relationship that should be able to be rationalized by the compiler? – Mike Aug 12 '13 at 23:37
  • Sorry, I edited my comment once I re-read your problem. Covariance is only allowed on interfaces. This is a very common problem: assuming that collections of some type have the same relationships as their contents. Co-/contra- variance are solutions to them, but unnecessary for your needs, but still worth a read if you are interested. – lukegravitt Aug 12 '13 at 23:40

1 Answers1

2

FieldFiller is also IFieldFiller but List<FieldFiller> is not a List<IFieldFiller>, you can cast it accordingly:

Fields =  temp.merged_fields
    .Select(f => (IFieldFiller)new FieldFiller { Name = f.name, NameSpace = f.@namespace, StoredProcedure = new StoredProcedure { Name = f.sproc1.name, Parameters = f.field_params.ToDictionary(p => p.sprocParam.name, p=>p.value)}})
    .ToList()

or, with .NET 4 you can use this(see: Covariance and Contravariance):

...
    .Select(f => new FieldFiller { ... })
    .ToList<IFieldFiller>();

Why it's not safe:

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939