Reputation: 93
This should sound like a really basic question, but I haven't been able to find an answer (even tho I know for sure there are plenty), I guess my Googling skills are bad, or maybe I don't know what to search for.
I have this code:
using System;
public class Program
{
public static void Main()
{
var service = new Service();
service.Execute();
}
}
public class Service
{
private int _foo;
public void Execute()
{
_foo = 1;
var bar = new Bar(_foo);
_foo = 2;
bar.WriteLine();
}
}
public class Bar
{
private readonly int _foo;
public Bar(int foo)
{
_foo = foo;
}
public void WriteLine()
{
Console.WriteLine(_foo);
}
}
How can I make it so it prints 2
? (basically the new value after Bar
has been initialized)
I tried using ref
but no luck.
Upvotes: 1
Views: 155
Reputation: 81473
What you are trying to do doesn't make sense for a value type
Value types and reference types are the two main categories of C# types. A variable of a value type contains an instance of the type. This differs from a variable of a reference type, which contains a reference to an instance of the type. By default, on assignment, passing an argument to a method, or returning a method result, variable values are copied. In the case of value-type variables, the corresponding type instances are copied.
Normally you would create this as a property and set it accordingly
Given
public class Bar
{
public Bar(int foo) => Foo = foo;
public int Foo {get;set;}
public void WriteLine() => Console.WriteLine(Foo);
...
Usage
public void Execute()
{
var bar = new Bar(1);
// set the property instead
bar.Foo = 2;
bar.WriteLine();
...
Upvotes: 2