Search code examples
c#classoopmethodscall

C# Calling variables from other classes


this is probably very simple, but I have always just made one big class and never tried make clean code. Now I am trying and experiencing errors..

So, this is the idea:

class1
{
    method1 { value 1; value 2 }
    method2 { value 3; value 4 }
    method3 { uses method4 from class2 }
}

class2
{
    method4 { uses values 1-4 from class1 }
}

I am doing it by calling: class1 c1 = new class1() in method4 and class2 c2 = new class2 in method3.

So this is what happens:

  • method1, method2 produce values 1-4
  • method3 calls class2 c2 = new class2
  • I get into class2, then into method4 and get null/0 values instead of what I made in first step.

Solution

  • Well, here is some code for you. I'm not sure it it's what you require. It might help you get started, though. You can try running it here: https://dotnetfiddle.net/#

    This is Class1. It exposes some of its data via properties.

    public class Class1
    {
        // these are properties
        public int Value1 { get; set; }
        public int Value2 { get; set; }
        public int Value3 { get; set; }
        public int Value4 { get; set; }
    
        public void Method1()
        {
            Value1 = 1;
            Value2 = 2;
        }
    
        public void Method2()
        {
            Value3 = 3;
            Value4 = 4;
        }
    
        public void Method3()
        {
            // uses method4 from class2 
            var c = new Class2();
            c.Method4();
        }
    }
    

    This is Class2. It calls methods from Class1 and accesses its properties.

    public class Class2
    {
        public void Method4()
        {
            //uses values 1-4 from class1 
            var c = new Class1();
    
            c.Method1();
            c.Method2();
    
            Console.WriteLine(c.Value1);
            Console.WriteLine(c.Value2);
            Console.WriteLine(c.Value3);
            Console.WriteLine(c.Value4);
        }
    }
    

    This uses both closes and shows the result:

    using System;
    
    public class Program
    {
        public static void Main()
        {
            var c1 = new Class1();      
            c1.Method3();
        }
    }