KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
In the following code, I am trying to have a method(Work) from class TestClass change the values of some variables in the main program without having to return them. The variables are passed by reference in the TestClass constructor. class Program { static void Main(string[] args) { int a, b, c, d; a = 5; b = 10; c = 20; d = 25; Console.WriteLine("Main before TestClass: a=" + a + " b=" + b + " c=" + c + " d=" + d); TestClass testObj = new TestClass(ref a,ref b,ref c,ref d); testObj.Work(); Console.WriteLine("Main after TestClass: a=" + a + " b=" + b + " c=" + c + " d=" + d); Console.ReadLine(); } } public class TestClass { int _a, _b, _c, _d; public TestClass(ref int a, ref int b, ref int c, ref int d) { _a = a; _b = b; _c = c; _d = d; } public void Work() { Console.WriteLine("Work before changing: a=" + _a + " b=" + _b + " c=" + _c + " d=" + _d); _a = 0; _b = 1; _c = 2; _d = 3; Console.WriteLine("Work after changing: a=" + _a + " b=" + _b + " c=" + _c + " d=" + _d); } } However this code returns : Main before TestClass: a=5 b=10 c=20 d=25 Work before changing: a=5 b=10 c=20 d=25 Work after changing: a=0 b=1 c=2 d=3 Main after TestClass: a=5 b=10 c=20 d=25 Is there any way to have the method change the values of the variables in the Main program? Thank you!
Tags (comma-separated)
Save Edits
Cancel