-1

I am trying to do something like this:

where DataTableLoader2 is a generic helper class

public static class DataTableLoader2 <T> where T : class, new (StringComparer)

Thanks for any help offered....

K

Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40
Keith Vinson
  • 771
  • 5
  • 10
  • 1
    Have you tried this? Checked any documentation? What have you attempted? – CBHacking Apr 16 '21 at 20:02
  • 4
    Here's the docs: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint – David Browne - Microsoft Apr 16 '21 at 20:05
  • I did I read through MS docs & googled around, I could find no mention of anything other than a parameter less constructor. I have also tried multiple permutations & combinations to see if I could back my way into something the compiler would take. So far no luck... – Keith Vinson Apr 16 '21 at 20:06
  • `I could find no mention of anything other than a parameter less constructor` - well, that's because ONLY the PARAMETERLESS constructor is allowed within constraint definition. – quetzalcoatl Apr 16 '21 at 20:07
  • 1
    https://xyproblem.info/ – Robert Harvey Apr 16 '21 at 20:08
  • 2
    @KeithVinson The answer to your question as asked is "no". But I suspect you have an X/Y problem here. You should ask a new question explaining what you're trying to achieve that makes you think you need this feature. – Logarr Apr 16 '21 at 20:08
  • 1
    After a lot of searching, I finally found a suitable preceding duplicate. While the title isn't perfect, please read the linked question in full before saying it's not a dupe :) As a bonus, the answer accepted there provides a very handy workaround. – quetzalcoatl Apr 16 '21 at 20:15
  • I think the intent of your question has been misunderstood. I'm pretty sure what you are looking for is just this `public static class DataTableLoader2 where T : StringComparer` You can have a base class like `StringComparer` as a where constraint. – TJ Rockefeller Apr 16 '21 at 20:24

1 Answers1

5

No, it can't. The purpose of new() is simply to enforce that T must have a default, parameterless constructor. If you want to enforce a generic having some common initialization then you should do it through either a base class, or an interface.

Logarr
  • 2,120
  • 1
  • 17
  • 29