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
Release: 2025-01-09 12:11:42
Original
219 people have browsed it

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:

public void AddFruit<T>() where T : BaseFruit
{
    BaseFruit fruit = new T(weight); /*new Apple(150);*/
    fruit.Enlist(fruitManager);
}
Copy after login

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:

return (T)Activator.CreateInstance(typeof(T), new object[] { weight });
Copy after login

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 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template