s.k.paul s.k.paul - 1 month ago 6
C# Question

Can not access a non-static member from nested class in C#

namespace DateTimeExpress
{
public class Today
{
private DateTime _CurrentDateTime;


public class Month
{
public int LastDayOfCurrentMonth
{
get
{
return DateTime.DaysInMonth( _CurrentDateTime.Year, _CurrentDateTime.Month);
}
}
}

public Today()
{

}
}
}


How can I access _CurrentDateTime

Answer

You can see an example that explains your problem in the C# Programming Guide at Nested Types paragraph where they say:

The nested, or inner type can access the containing, or outer type. To access the containing type, pass it as a constructor to the nested type.

Essentially you need to pass a reference to the container (Today class) in the constructor of the nested class (Month class)

public class Today
{
    private DateTime _CurrentDateTime;
    private Month _month;

    public int LastDayOfCurrentMonth { get { return _month.LastDayOfCurrentMonth; }}

    // You can make this class private to avoid any direct interaction
    // from the external clients and mediate any functionality of this
    // class through properties of the Today class. 
    // Or you can declare a public property of type Month in the Today class
    private class Month
    {
        private Today _parent;
        public Month(Today parent)
        {
            _parent = parent;
        }
        public int LastDayOfCurrentMonth
        {
            get
            {
                return DateTime.DaysInMonth(_parent._CurrentDateTime.Year, _parent._CurrentDateTime.Month);
            }
        }
    }

    public Today()
    {
        _month = new Month(this);
        _CurrentDateTime = DateTime.Today;
    }
    public override string ToString()
    {
        return _CurrentDateTime.ToShortDateString();
    }
}

And call it with something like this

Today y = new Today();
Console.WriteLine(y.ToString());
Console.WriteLine(y.LastDayOfCurrentMonth);
Comments