Jace
Jace

Reputation: 817

How to Implement Extension Method in Abstract Class

I'm developing an MVVM-based library and I'd like to incorporate this extension method for my ObservableObject abstract class.

public static ObservableObject  FirstOrDefaultInstance(this IEnumerable<ObservableObject> items)
   {
      return items.FirstOrDefault() ?? new ObservableObject();
   }

Obviously, this won't work. But how can my derived types inherit this extension with an implementation of their own default constructor?

Upvotes: 1

Views: 740

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

You can use new() generics constraint on generic method if specifying/inferring concrete type in invocation works for you:

public static FirstOrDefaultInstance<T>(this IEnumerable<T> items)
   where T: ObservableObject, new()
{
   return items.FirstOrDefault() ?? new T();
}

Upvotes: 2

Related Questions