Search code examples
c#arrayspropertiescalculatorbase-class

Get array of chars from a base class property


I'm relatively new to programming, here is what I want to do: I have a base class containing a property "Operator", its derivatives are classes for mathmatical operations, so the Operators are '-' '+' etc. Now I need to create an array of these Operators to use in my Calculator engine. I only have a list of the operation methods, how do I extract only the Operators and put them in an array? This is what I have already, but I'm asked to use the already existing Operators

char[] operatorArray = {'+', '-', '/', '*'};

            int indexOfLastOperatorBeforeSquare = leftOfSquare.LastIndexOfAny(operatorArray);

This is my base Class containing the Operator property:

public abstract class OperationBase
{
    public abstract string Operator { get; set; }
    public abstract string Execute(string leftOperator, string rightOperator);
}

and this is the constructor of the Addition Class as an example:

public Addition()
    {
        Operator = "+";
    }

Solution

  • Probably you've derived OperationBase in classes like Addition, Substraction, Division...

    If you store these implementations in a List<OperationBase> (i.e. adding instances to the whole list: list.Add(new Addition()); list.Add(new Subtraction()); and so on), you can extract the operators using LINQ:

    List<OperationBase> operations = new List<OperationBase>();
    operations.Add(new Addition());
    operations.Add(new Division());
    operations.Add(new Subtraction());
    
    IEnumerable<char> operators = operations.Select(operation => operation.Operator[0]);
    

    Now, the whole operators can be converted to array calling operators.ToArray(), which will contain the operators as characters:

    char[] operatorChars = operators.ToArray();
    

    Note that I had to obtain the operator character using operation.Operator[0]: your OperationBase defines that the operations provide their operator as string instead of char. If you want to avoid this, fix the whole property and turn it to char type, and the code will look as follows:

    IEnumerable<char> operators = operations.Select(operation => operation.Operator);