baconcow
baconcow

Reputation: 3

C# - How to pass ClassA's properties as ClassB's argument(s)?

I am sure the answer to the following is basic, but so is my knowledge of C#. I have searched around and not able to find an answer that works in my application. I have the following (simplified from my actual code, in notepad, so I hope I didn't mess up the syntax much). Since I cannot get it to work, I figure there is an error somewhere. My final code is much more complex. I want to be able to have dataA and dataB classes carry separate sets of properties as they each represent a different object. Hoping to learn more. Thanks you, in advance.

I get the following error:

'double' does not contain a definition for 'prop1' and no extension method 'prop1' accepting a first argument of type 'double' could be found (are you missing a using directive or an assembly reference?)

public class ClassA
{
    // Class constructor
    public ClassA(double arg1, double arg2)
    {
        prop1 = arg1;
        prop2 = arg2;
    }

    // Class properties
    public double prop1 { get; set; }
    public double prop2 { get; set; }
}

public class ClassB
    {
        // Class constructor
        public ClassB(double arg3)
        {
            var1 = arg3.prop1;
            var2 = arg3.prop2;
        }

        // Class properties
        public double var1 { get; set; }
        public double var2 { get; set; }
    }

class Program
{
    static void Main(string[] args)
    {
        ClassA dataA = new ClassA(1.0, 2.0);
        ClassB dataB = new ClassB(dataA);
        // end result: dataB.var1 and dataB.var2
    }
}

Upvotes: 0

Views: 49

Answers (1)

Bill
Bill

Reputation: 1479

Modify the constructor of ClassB to take ClassA:

public class ClassB
{
    // Class constructor
    public ClassB(ClassA arg3)
    {
        var1 = arg3.prop1;
        var2 = arg3.prop2;
    }

    // Class properties
    public double var1 { get; set; }
    public double var2 { get; set; }
}

Upvotes: 2

Related Questions