Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I restrict a class to be creatable only within another class?

Tags:

c#

oop

I've been breaking my brain to figure out how to do this in C#. I have a TextGrid class, which is essentially an MxN grid of text. I'd like to have a Cursor class that maintains an (X, Y) position in a TextGrid, as well as methods for moving the position, querying the current position, etc. Ideally, I'd like for this class to not be creatable outside of TextGrid, since it's useless without being logically attached to a TextGrid.

However, my approaches for tackling this aren't up to par: I've tried having 1) Cursor be a public class nested inside TextGrid with a private constructor, 2) Cursor be a private class nested inside TextGrid with a public constructor, and 3) Cursor be its own separate public class outside of TextGrid with a public constructor. #1 doesn't work because I'm not able to instantiate a Cursor from within TextGrid due to the private constructor. #2 doesn't work because I can't return the created Cursor object outside of TextGrid (e.g. a GetCursor() method) due to access restrictions. And #3 doesn't help at all.

Pretty much, what I'd like to do is have the equivalent of Java's Iterator in C#. Is this possible?

like image 502
Mark LeMoine Avatar asked Aug 08 '10 06:08

Mark LeMoine


2 Answers

Use #2, but return it by interface:

public interface ICursor
{

}

public class TextGrid
{
  private class Cursor : ICursor
  {
  }

  // This could be a property if it doesn't require much calculation.
  public ICursor GetCursor()
  { 
  }
}
like image 106
Matthew Flaschen Avatar answered Nov 15 '22 22:11

Matthew Flaschen


While using an interface to solve the problem is a good approach, if you just want to have every instance of the Cursor class associated with an instance of the TextGrid class, you can simply require the creator to pass an argument of type TextGrid to the constructor as such:

public class Cursor
{
    public Cursor(TextGrid owner)
    {
        ...
    }
}
like image 30
Allon Guralnek Avatar answered Nov 15 '22 20:11

Allon Guralnek