Home > database >  C# "generic value parameters"
C# "generic value parameters"

Time:11-12

Is there such a thing as "generic value parameters" to set specific values in the variable declaration instead of in the constructor? Look at this Example: I want to use something like this:

public class CalcObj<const int i> // Important: Only objects with the same "generic value parameter" can be assigned to this object.
{
    public CalcObj()
    {
        // Value of i must be set at declaration, not in constructor. Example:
        // CalcObj<5> variableName = new CalcObj<5>();
        // NOT:
        // CalcObj variableName = new CalcObj(5);
    }

    public int calc(int x)
    {
        return i * x;
    }
}

instead of this:

public class CalcObj1 : IAnyInterface
{
    public CalcObj1() { }

    public int calc(int x) { return 1 * x; }
}

public class CalcObj2 : IAnyInterface
{
    public CalcObj2() { }

    public int calc(int x) { return 2 * x; }
}
public class ...

CodePudding user response:

Like it or not, you're expected to use a field, which you can require in the constructor. Generics are only for types.

public class CalcObj : IAnyInterface
{
    private int multiplier;

    public CalcObj(int Multiplier) {multiplier = Multiplier;}

    public int calc(int x) { return multiplier * x; }
}
  • Related