Home >Backend Development >C++ >Can Generic Type Instantiation Handle Constructor Arguments in C#?

Can Generic Type Instantiation Handle Constructor Arguments in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-09 12:11:42198browse

Can Generic Type Instantiation Handle Constructor Arguments in C#?

C# generic type instantiation and constructor parameters

When building a generic type, a common question is: How to instantiate a constructor that requires parameters in a generic method? For example, the BaseFruit class has a constructor that receives a weight parameter of type integer.

How to instantiate fruits with a specified weight in a generic method?

The following code attempts to create a fruit instance with a specified weight in a generic method:

<code class="language-csharp">public void AddFruit<T>() where T : BaseFruit
{
    BaseFruit fruit = new T(weight); /*new Apple(150);*/
    fruit.Enlist(fruitManager);
}</code>

This approach is only possible if BaseFruit has a parameterless constructor that subsequently modifies the properties via member variables. However, in real applications, this may not be practical.

Alternative:

can use the Activator class:

<code class="language-csharp">return (T)Activator.CreateInstance(typeof(T), new object[] { weight });</code>

In this case, the T constraint on new() ensures that a public parameterless constructor exists at compile time, and the Activator class is responsible for the actual type creation.

Note:

While this scenario provides a workaround, the existence of the specific constructor must be verified in the code. Additionally, relying on this approach may indicate a problem at the code level and should be avoided in current versions of C#.

The above is the detailed content of Can Generic Type Instantiation Handle Constructor Arguments in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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