codingseb / ExpressionEvaluator

A Simple Math and Pseudo C# Expression Evaluator in One C# File. Can also execute small C# like scripts
MIT License
595 stars 99 forks source link

Change behavior to directly use the provided Variables dictionary #126

Closed AttilaSzobonya closed 2 years ago

AttilaSzobonya commented 2 years ago

Problem

The ExpressionEvaluator (EE) currently creates a copy ))of the provided variables dictionary as seen at line 904.

Description

At my use case I would like to receive the value modifications outside the EE which is now only possible if I copy the values back after evaluation. It also creates an inconsistency as if I modify a member of a reference variable (say A.Name = "something") then it does change it's value outside the EE. (Which it should of course, because of the reference call, and we cannot do anything about it) Also I have to re-assign the Variables property every time there is a possibility that a value has been changed outside the EE instance. This causes a lot of unnecessary memory copy for me.

Suggestion

I would make it at least an option to assign your own variables dictionary, but I just wouldn't think about and make it a must. I realize that the current solution has been chosen to introduce the possibility choose if we want the string comparer to be case sensitive or not, but exactly this solution prevents us to use any other equality comparer as well.

Summary

Using our own dictionary makes everything better. 🥳 (Except it might break someone's existing code, but this can be handled at library update 🤭 )

rkjack commented 2 years ago

It is already possible to create and update a persistent collection.

rkjack commented 2 years ago

image

AttilaSzobonya commented 2 years ago

This is what I meant by modifying a reference variable, but it is not a solution for the above mentioned difficulties.

codingseb commented 2 years ago

Hello @AttilaSzobonya Thanks for this issue.

Thanks @rkjack for your help to answer this issue. Yes evaluator.Context = _persist; work for this.

I also understand the need to have it on evaluator.Variables in some cases. Especially if you don't use the option evaluator.OptionCaseSensitiveEvaluationActive so I added an other option : evaluator.OptionVariablesPersistenceCustomComparer = true to keep the evaluator.Variables dictionary as provided. By default it will be set to false to keep compatibility.

Of course if you set it to true the option evaluator.OptionCaseSensitiveEvaluationActive is not applied to variables anymore it's up to you to provide the Comparer you want for your dictionary.

I also added 2 more constructors to set the option to true and set the variables in the constructor together.

It will be available in version 1.4.36.0

AttilaSzobonya commented 2 years ago

Hello! Thank you @codingseb! Your work is much appreciated! Have a blessed day. 🥳

codingseb commented 2 years ago

Version 1.4.36.0 is published