Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor Signature Constraints on Type Parameters

public static IEnumerable<TV> To<TU, TV>(this IEnumerable<TU> source) where TV : new(TU)
{
    return source.Select(x => new TV(TU));
}

The problem is that I can't give the new(TU) constraints.

  • Is there any solution to this problem?
like image 373
Amir Rezaei Avatar asked Jan 27 '26 12:01

Amir Rezaei


2 Answers

I've got two approaches for you:

Firstly using Activator.CreateInstance

public static IEnumerable<TV> To<TU, TV>(this IEnumerable<TU> source)
{ 
  return source.Select(m => (TV) Activator.CreateInstance(typeof(TV), m));
}

Secondly, you could use interfaces to define properties rather than use parameterized constructors:

public interface IRequiredMember
{}

public interface IHasNeccesaryMember
{
  IRequiredMember Member
  {
    get;
    set;
  }
}

public static IEnumerable<TV> To<TU, TV>(this IEnumerable<TU> source)
            where TV : IHasNeccesaryMember, new()
            where TU : IRequiredMember
 {
    return source.Select(m => new TV{ Member = m });
 }

The first method works but feels dirty and there is the risk of getting the constructor call wrong, particularly as the method is not constrained.

Therefore, I think the second method is a better solution.

like image 150
Xhalent Avatar answered Jan 30 '26 02:01

Xhalent


Maybe pass in a Func which can create a TV from a TU:

public static IEnumerable<TV> To<TU, TV>(
    this IEnumerable<TU> source, 
    Func<TU, TV> builder)
    where TV : class
{
    return source.Select(x => builder(x));
}

and call with

tus.To(x => new TV(x));
like image 44
Graham Clark Avatar answered Jan 30 '26 01:01

Graham Clark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!