Home >Backend Development >C++ >Can C# Generic Methods Constrain Type Parameters to Specific Constructors?

Can C# Generic Methods Constrain Type Parameters to Specific Constructors?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-14 16:01:44847browse

Can C# Generic Methods Constrain Type Parameters to Specific Constructors?

Constructor constraints with parameter specification in C#

In C#, generic methods allow constraints to be imposed on type parameters. For example, the following code shows a constraint that requires parameter type T to have a parameterless constructor:

<code class="language-csharp">public class A {

    public static T Method<T>(T a) where T : new() {
        //...do something...
        return new T();
    }

}</code>

This begs the question: can we refine the constraints and specify that T should have a constructor that accepts a float[,] argument? Unfortunately, the following attempt fails to compile:

<code class="language-csharp">public class A {

    public static T Method<T>(T a) where T : new(float[,] u) {
        //...do something...
        return new T(new float[0,0]);
    }

}</code>

Solution

Since this constraint cannot be used, we can adopt a workaround and use a delegate to initialize an object of type T:

<code class="language-csharp">public class A {

    public static void Method<T>(T a, Func<float[,], T> creator) {
        //...do something...
    }

}</code>

The above is the detailed content of Can C# Generic Methods Constrain Type Parameters to Specific Constructors?. 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