Home > other >  How to implement an interface that contains an interface?
How to implement an interface that contains an interface?

Time:12-31

I have two interface:

public interface IPerson
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public ILocation LocationOfBirth { get; set; }
}
public interface ILocation
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

Now I want to implement them like this:

public class Location : ILocation
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}
public class Person : IPerson
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Location LocationOfBirth { get; set; }
}

But c# is angry on me:

Property 'LocationOfBirth' cannot implement property from interface 'IPerson'. Type should be 'ILocation'.

Why is this so when Location fulfills the all requirements of ILocation?

I want to use Person as a model for EntityFramework, so I cannot use ILocation. What to do?


Edit: In my application, the implementations of the interfaces are not in the scope of the interfaces, so I cannot define IPerson with the Location implementation.

CodePudding user response:

if you want to use your class in EF try this code. EF will have a concrete class version, and if you need an interface somewhere else, it will be working too.

public class Person : IPerson
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    
    [NotMapped]
    public ILocation LocationOfBirth 
    {
        get {return BirthLocation;}
        set {BirthLocation= (Location) value; 
    }
    public Location BirthLocation {get; set;}
}

CodePudding user response:

The c# precompiler resolves ILocation to the concrete class Location upon instantiation or assignment during usage

public class Person : IPerson
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public ILocation LocationOfBirth { get; set; }
}

CodePudding user response:

This can be done easily if you use explicit interface implementation:

public class Person : IPerson
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Location LocationOfBirth { get; set; }
    // Explicit interface implementation here
    ILocation IPerson.LocationOfBirth {
        get => this.LocationOfBirth; 
        set => this.LocationOfBirth = value as Location;
    }
}

  • Related