Home > Backend Development > C++ > How Can I Pass Arguments to a Generic Constructor in C# Using the `new()` Constraint?

How Can I Pass Arguments to a Generic Constructor in C# Using the `new()` Constraint?

Mary-Kate Olsen
Release: 2025-01-22 13:57:11
Original
211 people have browsed it

How Can I Pass Arguments to a Generic Constructor in C# Using the `new()` Constraint?

Using new() constraints in C# to pass parameters to generic constructors

When adding elements to a list, trying to create a new object of type T with constructor parameters, you may encounter a compilation error stating that the parameters cannot be provided when creating a variable instance. This error occurs even if there are constructor parameters in the class.

To solve this problem, new() constraints of generic types must be used. While this constraint allows the creation of parameterless instances, it is not sufficient for the case where constructor parameters are included.

The alternative is to introduce a parameter so that the object is created based on the parameter. Functions can accomplish this efficiently.

<code class="language-csharp">public static string GetAllItems<T>(..., Func<ListItem, T> del) {
  ...
  List<T> tabListItems = new List<T>();
  foreach (ListItem listItem in listCollection) 
  {
    tabListItems.Add(del(listItem));
  }
  ...
}</code>
Copy after login

This function can be called using a lambda expression that creates a new object with the required parameters:

<code class="language-csharp">GetAllItems<Foo>(..., l => new Foo(l));</code>
Copy after login

The above is the detailed content of How Can I Pass Arguments to a Generic Constructor in C# Using the `new()` Constraint?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template