2
private static void ApplyChanges<TEntity>(TEntity root) where TEntity : class, IObjectWithState
        {
            using (var context = new BreakAwayContext())
            {
                context.Set<TEntity>().Add(root);
                CheckForEntitiesWithoutStateInterface(context);

                foreach (var entry in context.ChangeTracker.Entries<IObjectWithState>())
                {
                    IObjectWithState stateInfo = entry.Entity;
                    entry.State = ConvertState(stateInfo.State);
                    if (stateInfo.State == State.Unchanged)
                    {
                        var databaseValues = entry.GetDatabaseValues();
                        entry.OriginalValues.SetValues(databaseValues);
                    }
                }

                context.SaveChanges();
            }
        } 

I am reading a book about Entity Framework and faced a function declaration like above. As my understanding; where clause is defining type of TEntity. So if we choose to define type of TEntity, why not use strongly typed parameter instead of using Generics?

Am I missing something? And what is the terminology is being used for this type of declaration?

Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158
  • 3
    That's a [generic type parameter constraint](http://msdn.microsoft.com/en-us/library/d5x73970.aspx). – Blorgbeard Jul 30 '14 at 04:20
  • @Blorgbeard: I think he already knows that, he's asking why using this instead of using a strongly typed parameter. – Transcendent Jul 30 '14 at 04:21
  • The parameter *is* strongly typed. Perhaps I don't understand the question. – Blorgbeard Jul 30 '14 at 04:23
  • @Blorgbeard As far as I can tell they want to know why the method signature doesn't simply use `IObjectWithState` instead of making it generic. – Kyle Jul 30 '14 at 04:25
  • @Blorgbeard Thanks for the reference. "Multiple interface constraints can be specified. The constraining interface can also be generic." statement totally makes sense, there we can limit/expand what type of parameter our function is accepting. I wish I would mark your comment as answer :) – Teoman shipahi Jul 30 '14 at 04:27
  • Regarding your question, "If we choose to define type of `TEntity`, why not use strongly typed parameter instead of using Generics?"; with a generic type parameter constraint, you are able to elegantly constrain the parameter to inherit from one class and implement several interfaces not already implemented by said class. A strongly-typed parameter cannot do so in a single declaration. – Mike Jul 30 '14 at 04:35

0 Answers0