leojnxs
leojnxs

Reputation: 127

What the difference between these two types of inheritance?

I'm coding a repository and i was with the following problem:

The code below shows an error as if the repository were inheriting the IRepository interface and type T was inheriting IDisposable

public class GenericRepository<T> : IGenericRepository<T> where T : class, IDisposable

So, when i changed the inheritance order, the problem was solved

public class GenericRepository<T> : IDisposable, IGenericRepository<T> where T : class

My solution for this problem its correct?

Upvotes: 1

Views: 116

Answers (4)

Alex
Alex

Reputation: 35409

The former:

public class GenericRepository<T> : IGenericRepository<T> where T : class, IDisposable

enforces the IDisposable constraint on type T, whereas:

public class GenericRepository<T> : IDisposable, IGenericRepository<T> where T : class

requires GenericRepository<T> to implement IDisposable.

It's up to you to decide how you want to design your repositories - I'd opt for the latter. I'd argue its the repository's responsibility to dispose of its' resources.

Upvotes: 2

Gabriel Boya
Gabriel Boya

Reputation: 771

public class GenericRepository<T> : IGenericRepository<T> where T : class, IDisposable

constrains type parameter T to implement IDisposable.

With the second code you show, it is the GenericRepository<T> which is required to implement IDisposable interface, no matter of what T is.

Upvotes: 3

Evgeni
Evgeni

Reputation: 3343

Well, your first line explicitly says that T must be IDisposable.

Second line says that your GenericRepository must be IDisposable. If that is your intention - yes, your solution is correct.

Upvotes: 1

John Koerner
John Koerner

Reputation: 38077

In your first code snippet the IDisposable is part of the constraint.

In your second code snippet, the IDisposable is an interface that your GenericRepository<T> implements.

Upvotes: 3

Related Questions