Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a class implementation in C#

Can I replace (or override) a class definition with one of my own implementation?

Explanation:

  • I have a class with a System.Random instance, and I am trying to test it without modifying its original code...
  • So I am planning to replace Random class with one of my own implementation, that allows controlling generated sequence.. Please see this question.

`

class foo
{
    Random r=new Random();
    double bar()
    {
         double ans=r.NextDouble();
         .....// evaluate ans
         return ans;
    }
}

`

What are the possible ways that I can replace implementation of Random class with another one without changing (or with minimum changes) the original code file??

Edit:
One solution is to inherit Random class and modify it... but that requires changing each Random instance with the inherited one... I do not want to modify the code, because I am just testing it!!
Edit 2:
Can I say in C#: "Each Random class in this file is MyNamespace.Random not System.Random" ??

like image 411
Betamoo Avatar asked Jan 25 '26 05:01

Betamoo


1 Answers

EDIT: As ChaosPandion points out, to test the logic in the method it would be better to take a double parameter i.e. double bar(double input) { ... }, but if you have a reason to need to inject your own source of randoms, you could use one of these approaches:

You could modify bar to take a Func<double> to obtain values from:

double bar(Func<double> source)
{
    double ans = source();
    //evaluate ans
    return ans;
}

Then you can inject your own implementation for testing, and in the main program use:

Random r = new Random();
double ans = bar(r.NextDouble);

Alternatively you could create your own IRandom interface and then implement a wrapper around the real Random class and use mocks for testing:

interface IRandom
{
    double Next();
}

public class RandomWrapper : IRandom
{
    private Random r = new Random();
    public double Next()
    {
        return this.r.NextDouble();
    }
}
like image 183
Lee Avatar answered Jan 27 '26 19:01

Lee