Search code examples
c#interfacegeneric-method

Generic method working for one class but not the other, with the same interface


I have two classes

[DataContract]
public class HiveReference : IGUID
{
    [BsonId]
    [DataMember]
    public Guid GUID{ get; set; }
    ....
}
...

[DataContract]
public class HiveByteChunk : IGUID
{
    [DataMember]
    [BsonId]
    public Guid GUID { get; set; }
    ...
}

My interface ...

public interface IGUID
{
    Guid GUID {get;set;}
}

Then I have an extension method ...

public static void InsertIfNotExists<T>(this T member) where T: IGUID
{
    if (!(member).Exists())
    {
        member.Insert();
    }
}

public static void Insert(this object member) 
{
    DBHelper.Insert(member);
}

Then my implementation code ...

HiveReference hf = new HiveReference();
hf.InsertIfNotExists();

HiveByteChunk chunk = new HiveByteChunk();
chunk.InsertIfNotExists();

The last line breaks, with this compiler error:

Error   CS0311
    The type 'HiveLibrary.HiveBytes.HiveByteChunk' cannot be used as type parameter 'T' in the generic type or method 'Extensions.InsertIfNotExists<T>(T)'.
    There is no implicit reference conversion from 'HiveLibrary.HiveBytes.HiveByteChunk' to 'HiveLibrary.IGUID'.

If both classes implements the interface, why would the first one be able to call the extension, but not the last? Am I missing something obvious?


Solution

  • The problem was that I had a duplicate interface, in a different namespace. Once I removed that, everything worked as intended.