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?
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()
{
}
}
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)
{
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With