Reputation: 817
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
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