C# How outer class can create instance of inner private class

T.Zacks 3,996 Reputation points
2022-04-29T18:55:44.207+00:00

please see the below code and we know that we can not create instance of private class directly but here outer class can create instance of inner class....how it is getting possible ?

also tell me how to access inner class by interface instead of direct instance creation. please guide me. thanks

class Order
{
    private List<OrderLine> _orderLines = new List<OrderLine>();

    public void AddOrderLine(string product, int quantity, double price)
    {
        OrderLine line = new OrderLine();
        line.ProductName = product;
        line.Quantity = quantity;
        line.Price = price;
        _orderLines.Add(line);
    }

    public double OrderTotal()
    {
        double total = 0;
        foreach (OrderLine line in _orderLines)
        {
            total += line.OrderLineTotal();
        }
        return total;
    }

    // Nested class
    private class OrderLine
    {
        public string ProductName { get; set; }
        public int Quantity { get; set; }
        public double Price { get; set; }

        public double OrderLineTotal()
        {
            return Price * Quantity;
        }
    }
}
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-04-29T19:52:45.417+00:00

    private means the type is defined for the scope. if a class define a private class, only that class can reference the type.

    for a class to have an interface, it must inherit and implement a defined interface. the interface could be public, even if the class is private,

    sample:

    using System;
    public class Program
    {
        public static void Main()
        {
            var foo = new Foo();
            foo.Bar.Echo("hello"); //works
            //foo.Bar.Echo2("hello"); //compile error - undefined
        }
    
        public interface IBar
        {
            void Echo(string s);
        }
    
        public class Foo
        {
            public readonly IBar Bar;
            public Foo() 
            { 
                Bar = new _Bar();
    
                // cast object to private class to call class method
                ((_Bar) Bar).Echo2("Foo Created");
            }
            private class _Bar : IBar
            {
                // interface method
                public void Echo(string s) { Console.WriteLine(s); }
                // class only method
                public void Echo2(string s) { Console.WriteLine(s); }
            }
        }
    }
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.