Click here to Skip to main content
15,889,472 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to access private constructor in other class. Can it is possible through chaining of constructor. I tried following code for it but it is not allowed.

in following code i declared variable k1=1 in class then change it in private constructor k1=2. when i create a object of other constructor which is parameterized and public also. I called it. but private constructor is not called.


please help.

What I have tried:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        int k1 = 1;
        private Program()
        {
            k1 = 2;


        }
        public Program(int k)
        {
            k = k1;
        }

        public void ftr()
        {

            Console.WriteLine(k1);
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            gtr g = new gtr();
            g.main();
        }
    }

    class gtr
    {
        Program p=new Program(1);

      public   void main()
        {
            p.ftr();
        }



    }
}
Posted
Updated 6-Jul-16 14:14pm
v2

You can't. Private means that it is only accessible inside the class it's declared in.

You've also got a couple of variables reversed in your constructor that takes an int as a parameter. It should be:
C#
public Program(int k)
{
    k1 = k;
}
 
Share this answer
 
v2
Comments
Maciej Los 7-Jul-16 1:31am    
5ed!
You should first address the design of your classes if you find yourself in this situation.
c# - Why do we need a private constructor? - Stack Overflow[^]

Here is a hack using reflection that you may wish to try:
Accessing a Private Constructor from Outside the Class in C# - Stack Overflow[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900