Rye
Rye

Reputation: 2311

Getting values from a multiple constructor

Here is the sample code:

class Class1
{
    string a;

    public Class1(string over) : base()
    {
       this.a = over;
       Console.WriteLine(a);
    }

    public Class1(bool check)
    {
       if(check)
         Console.WriteLine(a);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Class1 myClass1 = new Class1("test");
        Class1 myClass2 = new Class1(true);
        Console.ReadLine();
    }
}

What I want to happen is to get the value of string a from the 1nd Constructor Class1(string) and display it to Constructor Class1(bool). How can I do that?

Upvotes: 0

Views: 89

Answers (4)

MoSlo
MoSlo

Reputation: 2860

You have two different instances of Class1: myClass1 and MyClass2 If 'a' needs to be shared across instances, then you can make it static.

That way, setting 'a' in any instance of Class1 will apply to all instances.

Upvotes: 2

Emond
Emond

Reputation: 50682

Pass myClass1 to myClass2 in a method call (or in the constructor)

It is hard to tell what to do because Class1, a, over, check. They don't make sense to me.

Upvotes: 0

djeeg
djeeg

Reputation: 6765

This should work, but i dont think you should be doing that.

class Class1 {     

    static string a;  

    public Class1(string over) : base() {        
        a = over;        
        Console.WriteLine(a);     
    }      
    public Class1(bool check)     {        
        if(check)          
            Console.WriteLine(a);     
        } 
    }  

    class Program {     
        static void Main(string[] args)     {         
            Class1 myClass1 = new Class1("test");         
            Class1 myClass2 = new Class1(true);         
            Console.ReadLine();     
        } 
    } 
}

Upvotes: 0

froeschli
froeschli

Reputation: 2890

Make string astatic. That way, all instances of Class1 reference the same string.

Upvotes: 1

Related Questions