Skip to content

Instantly share code, notes, and snippets.

@adriang133
Created February 3, 2016 08:46
Show Gist options
  • Save adriang133/30553a7430a8d6a5864f to your computer and use it in GitHub Desktop.
Save adriang133/30553a7430a8d6a5864f to your computer and use it in GitHub Desktop.
Custom implemtentation of logical expressions
namespace CustomLogicalExpressions
{
public enum LogicalOperator
{
And, Or, Xor, Not
}
public abstract class LogicalExpression
{
public bool Evaluate(params string[] parameters)
{
return Evaluate(new HashSet<string>(parameters));
}
public abstract Boolean Evaluate(HashSet<String> parameters);
}
public class UnaryLogicalExpression : LogicalExpression
{
public LogicalOperator Operator { get; set; }
public LogicalExpression Expression { get; set; }
public override bool Evaluate(HashSet<String> parameters)
{
bool expressionEvaluation = Expression.Evaluate(parameters);
switch(Operator)
{
case LogicalOperator.Not:
{
return !expressionEvaluation;
}
default:
throw new InvalidOperationException("Invalid unary operator");
}
}
public UnaryLogicalExpression(LogicalOperator Operator, LogicalExpression Expression)
{
this.Operator = Operator;
this.Expression = Expression;
}
}
public class BinaryLogicalExpression : LogicalExpression
{
public LogicalExpression LeftSide { get; set; }
public LogicalExpression RightSide { get; set; }
public LogicalOperator Operator { get; set; }
public override bool Evaluate(HashSet<String> parameters)
{
bool leftSideResult = LeftSide.Evaluate(parameters);
bool rightSideResult = RightSide.Evaluate(parameters);
switch(Operator)
{
case LogicalOperator.And:
{
return leftSideResult && rightSideResult;
}
case LogicalOperator.Or:
{
return leftSideResult || rightSideResult;
}
case LogicalOperator.Xor:
{
return leftSideResult ^ rightSideResult;
}
default:
{
throw new InvalidOperationException("Operator not valid!");
}
}
}
public BinaryLogicalExpression(LogicalOperator Operator, LogicalExpression LeftSide, LogicalExpression RightSide)
{
this.Operator = Operator;
this.LeftSide = LeftSide;
this.RightSide = RightSide;
}
}
public class LogicalParameter : LogicalExpression
{
public string Name { get; set; }
public bool Value { get; set; }
public override bool Evaluate(HashSet<String> parameters)
{
return parameters.Contains(Name);
}
public LogicalParameter(string Name)
{
this.Name = Name;
}
public LogicalParameter(string Name, bool Value)
{
this.Name = Name;
this.Value = Value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment