Alex Rivera | Logout

Modifying parameter values before sending to Base constructor

Asked 2009-10-30T18:10:52.497
50

The title may be a bit ambiguous, but I couldn't think of a better way to word this.

I realize that I can not call a derived constructor prior to calling a base constructor, but can I somehow modify/create parameters values prior to passing them to the base?

For example,

public enum InputType
{
    Number = 1,
    String = 2,
    Date = 3
}

public class BaseClass
{
    public BaseClass(InputType t)
    {
        // Logic
    }
}

public class DerivedClass : BaseClass
{
    public DerivedClass(int i)
        : base(value)
    // Can I do something to infer what value should be here?
    {
        // Logic
    }
}

If I have a derived class that can infer the value required for the base constructor (in this example, InputType.Number would be valid for an int,) is there a way to modify and/or create values that are passed to the base constructor prior to the derived constructor executing?

Edit
Report

1 Answer

7

You can use a static method to compute a value to pass to the base constructor.

public class DerivedClass :
    BaseClass
{
    public
    DerivedClass(int i) :
        base(ComputedValue(i))
    {
    }

    public static InputType
    ComputedValue(int i)
    {
        return InputType.Number; // or any other computation you want here
    }
}
answered 2009-10-30T18:16:05.640

Your Answer