Nested Classes in C#
Is this the right way or is there an easier, smaller way to archive this?


It depends on how you define the right way. Is your goal short and small code or is your goal testability and maintainability? These two goals are mutualy exclusive.



If you want to have it short then of course there is a way. You don't need the nested class at all.

class NestedTest
{
    public int Position { get; private set; }

    public void Left()
    {
        Console.Write("&lt;-");
        Position--;
    }
}




If you want to have maintainable code then you need to write more code and correctly use dependency injection and possibly use a few interfaces as abstractions. Nested public classes are a bad style anyway so you should avoid them.

This is how such an implementation could look like. The NestedTest gets an interface that allows accesing its Position. Its constructor also requries a lambda that lets you specify the navigator for this instance.

public interface IPositionable
{
    int Position { get; set; }
}

class NestedTest : IPositionable
{
    public int Position { get; set; }

    public INavigator Navigator { get; }

    public NestedTest(int num, Func&lt;IPositionable, INavigator&gt; createNavigator)
    {
        Position = num;
        Navigator = createNavigator(this);
    }
}


Where the Navigator is now also abstracted by an interface and can be faked for testing or exachnged for another navigator later:

public interface INavigator
{
    void Left();
}

public class Navigator : INavigator
{
    private IPositionable _positionable;

    public Navigator(IPositionable positionable)
    {
        _positionable = positionable;
    }

    public void Left()
    {
        _positionable.Position--;
    }
}




It's up to you to decide. Shortest code possible or testable and maintainable?