1

Is there any practial reason to create interface for abstract class? I encountered such thing:

public interface IEntity<T> 
{
    T Id { get; set; }
}

public abstract class BaseEntity { 
}

public abstract class Entity<T> : BaseEntity, IEntity<T> 
{
    public virtual T Id { get; set; }
}

and i really don't understand what is the difference between that and this code, because IEntity is not a thing i whould use more than once:

public abstract class BaseEntity { 
}

public abstract class Entity<T> : BaseEntity
{
    public virtual T Id { get; set; }
}

Thanks!

Alexey Koptyaev
  • 187
  • 2
  • 16
  • What are you trying to accomplish? What is your goal, and why have you started to solve your problem by doing this? It's impossible to say what is a good idea and what isn't without knowing what problem you are trying to solve. – sara Mar 21 '16 at 14:25
  • http://stackoverflow.com/questions/14091837/c-sharp-abstract-class-implementing-an-interface, http://programmers.stackexchange.com/questions/163641/interfaces-on-an-abstract-class, try searching. – CodeCaster Mar 21 '16 at 14:26
  • Some guidance from Microsoft: https://msdn.microsoft.com/en-us/library/scsyfw1d%28v=vs.71%29.aspx – Matthew Watson Mar 21 '16 at 14:29
  • kai, i want to desribe structure of database entities. I thought that it would be nice to make BaseEntity class with implementation of general properties and inherit other classes from it. – Alexey Koptyaev Mar 21 '16 at 14:39
  • @AlexeyKoptyaev The fact that the suggested base-class would contain general properties or methods, is critical for its reason to exist, and it something you should have mentioned in the question. – Maarten Mar 21 '16 at 14:42
  • @CodeCaster Thanks, the first link is exatly what i wanted to know. All searches showed only "difference between abstract class and interface". – Alexey Koptyaev Mar 22 '16 at 07:43

2 Answers2

0

Since the BaseEntity class does actually add any properties of methods, yes, it is completely different from the interface. The interface defines a property Id of type T, and that interface (contract) can be used in other locations in your application.

The base class as it is now, is useless IMHO.

A base class which would implement the interface for you is something that would be usable, like this:

public interface IEntity<T> {
    T Id { get; set; }
}

public abstract class BaseEntity<T>: IEntity<T> { 
    public virtual T Id { get; set; }
}

public abstract class Entity<T> : BaseEntity<T> {
    // No need to implement the Id property, we already have it inherited
}
Maarten
  • 22,527
  • 3
  • 47
  • 68
0

Here is the same thing with correct answer that i wanted to know: c# Abstract Class implementing an Interface

Thanks everyone for help.

Community
  • 1
  • 1
Alexey Koptyaev
  • 187
  • 2
  • 16