Reputation: 19
How does object reference work in c# - I tried this, I am currently trying have an object being an reference to another object instance.
I need this in a class I am building
public class TransactionalProducer
{
private readonly IMessageBusProducer producer;
public TransactionalProducer (IMessageBusProducer bus, bool hasTransactionInitialized)
{
producer = bus;
if(hasTransactionInitialized)
{
producer.InitTransactions();
}
producer.BeginTransaction();
}
}
It looks like when I create a new TransactionalProducer
the producer
instance will be set as an new instance, where the values is taken from the function parameter bus
, and not be reference to the one being parsed via the constructor.
How do I make sure that when an new TransactionalProducer
object is being instantiated via the constructor public TransactionalProducer (IMessageBusProducer bus, bool hasTransactionInitialized)
is the producer
set as an object reference to bus
, and not create a new IMessageBusProducer
with the same parameters as function param bus
Upvotes: 0
Views: 784
Reputation: 43860
String objects are immutable: they cannot be changed after they have been created. b = "let me rewrite this" created a new object in a hip and assign the address of this object to b. c is still having the addres of an old object.
If you want to bind two variables try to use references.
string b = "This is changed";
ref string c = ref b;
Console.WriteLine(c);
b = "let me rewrite this";
Console.WriteLine(c);
b = "let me rewrite this again";
Console.WriteLine(c);
c = "let me reverse";
Console.WriteLine(b);
Console.WriteLine(c);
output
This is changed
let me rewrite this
let me rewrite this again
let me reverse
let me reverse
I don't understand what are trying to reach but try this, it could be working for you.
public TransactionalProducer (ref IMessageBusProducer bus, bool hasTransactionInitialized)
it will reach your inside busproducer, but I am not sure if it can cause a memory leak.
Upvotes: 2