0

I'm currently reading a book on design patterns which is written towards java, but would like to code examples in both Java and C#. Right now I'm trying to implement the strategy pattern in C#, and while I've found a lot of examples online, my current problem is something that I want to figure out the most.

In the Java example I have an abstract class and then a class that extends that abstract class. In the abstract class I declare, but don't instantiate, variables of an interface, which are then instantiated in the extended class.

Interface:

public interface MathStuff{
    public void add();
}

Abstract:

public abstract class Math{
    MathStuff mathStuff;

    public Math(){}

    public void addStuff(){
        mathStuff.add();
    }
}

Extended Class:

public class DoStuffWithMath extends Math{
    public DoStuffWithMath(){
        mathStuff = new RandomClass();
    }
}

Now I would really like to replicate this in C#. The C# code is essentially the same. I have an interface, an abstract class, and a class that I assume is extending the abstract class. I am not as familiar with C#. That class looks like this.

class DoStuffWithMath : Math{
    public DoStuffWithMath(){
        mathStuff = new RandomClass();
    }
}

The problem with the C# code is where i try to say "mathStuff = new RandomClass()". Any help or reading material would be appreciate.

PlainPat
  • 65
  • 1
  • 2
  • 10
  • 2
    If you declare an instance member without an access modifier in C#, it is considered `private`. You'll need something like `protected`. – Sotirios Delimanolis Jan 08 '15 at 02:59
  • 1
    Check out http://stackoverflow.com/questions/295224/what-are-major-differences-between-c-sharp-and-java and links. There are some differences between Java and C# (virtual, default access specifiers,...) that makes copy-pasted Java code not to work the same in C#. – Alexei Levenkov Jan 08 '15 at 03:05

1 Answers1

2

Explicitly adding protected would fix the issue (to override default private access):

public abstract class Math{
    protected MathStuff mathStuff;

    public Math(){}

    public void addStuff(){
        mathStuff.add();
    }
}

Note that depending on your needs either passing mathStuff as constructor of base class or using property instead of field would be better solution.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179