0

I am new to C#. I have a class with some methods in it, who use the solver object. But, for each of the method i need to again create an instance of solver object to use it. Can some one tell me how to avoid doing this by using interfaces? Making an interface is not a problem, but how to use it once it has been made??

Eg: This is my interface, that contains a solver

 public interface ISolver
    {
        public void Solve(Solver s);

    }

This is a method that implements ISolver interface

 public void Solve(Solver s)
        {
            Context ctx = new Context();
            ctx.MkSolver();

        }

I want to use this inside some methods(note: I have only one single class that contains different methods) One of the method is as follows:

public void MyCheck(Expression expr)
{
    BoolExpr boolVal = dispatch(expr);
    Solver s = ctx.MkSolver();
    Console.WriteLine(boolVal);
    s.Assert(boolVal);
    Console.WriteLine("\n ");
    Console.WriteLine(s.Check());
    Console.WriteLine(ReturnTrueFalse(s));
    Console.WriteLine("\n ");
}

and the other is:

public bool isContradiction(Expression expr)
{
    BoolExpr boolVal = dispatch(expr);
    Solver s = ctx.MkSolver();
    s.Assert(boolVal);
    Status result = s.Check();
    return result == Status.UNSATISFIABLE;
}

How to stop using Solver s = ctx.MkSolver(); in each and every method by using this interface. Any help would be appreciated. Thanks.

user5440565
  • 73
  • 1
  • 8

1 Answers1

1

I can't see how you want to get rid of the line Solver s = ctx.MkSolver() by using an interface. Instead I would make store the Solver instance in a member variable of your class. And maybe add a property for easy use:

public class YourClass
{
    private Solver _solver;
    private Solver MySolver
    {
        get {
            if (_solver == null) _solver = ctx.MkSolver();
            return _solver;
        }
    }

    // ...

The code you show in your question suggests that ctx is availabe in the scope of your class, so I used it in this property, too.

You can now use this property in your methods:

public void MyCheck(Expression expr)
{
    BoolExpr boolVal = dispatch(expr);
    Console.WriteLine(boolVal);
    MySolver.Assert(boolVal); // use property
    Console.WriteLine("\n ");
    Console.WriteLine(MySolver.Check());
    Console.WriteLine(ReturnTrueFalse(s));
    Console.WriteLine("\n ");
}

And:

public bool isContradiction(Expression expr)
{
    BoolExpr boolVal = dispatch(expr);
    MySolver.Assert(boolVal);
    Status result = MySolver.Check();
    return result == Status.UNSATISFIABLE;
}
René Vogt
  • 43,056
  • 14
  • 77
  • 99