I would like to initialize an object of type B from another class A, why I still get null? Is it possible to do it without using ref and out modifiers?
class A
{
public void Initialize(B value)
{
if (value == null)
{
value = new B();
}
}
}
class B
{
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = null;
a.Initialize(b);
}
}
[upd.] I thought the b variable could be passed by ref because of it’s the instance of the class.
It is possible, just make Initialize() a function:
And call it like:
This is a good solution, the data flow is clearly visible. No surprises.
But otherwise, just use a
ref(not anout) :public void Initialize(ref B value)and calla.Initialize(ref b);To answer that you need very precise wording:
bis not the instance of a class.bis a reference to an instance. Instances never have a name.And
bis treated just like a value type: the reference is passed by value to the method. Unless you useref.