Bronsoner Bronsoner - 1 year ago 66
C# Question

c# + programming logic - Can I access a constructor object from constructed object?

Please forgive me not beign super precise about this, but I am a c# noob and only learning programming. This is a problem I can't really test at this moment, but have to make a decision how to approach it.

I have a SampleClass:

public class SampleClass {
string Name;
SecondClass SecondClass;
string Attribute;
public SampleClass (string Name, SecondClass SecondClass)
this.Name = Name;
this.SecondClass = SecondClass;
Attribute = SecondClass.HakunaMatata;

And a SecondClass

public class SecondClass{
public string HakunaMatata;
public SecondClass (string HakunaMatata){
this.HakunaMatata = HakunaMatata;

so far so good. Now I need to know if I can add to SampleClass a function to change HakunaMatata from Second class?

if (Name == "Simba"){
SecondClass.HakunaMatata = "Dont'w worry, be happy"}

by inserting this code into SampleClass, will I change the value of SecondClasses object used to construct SampleClass or is the programm making a copy of it for purpose of construction? Will it change the SampleClass Attribute on the next instance on SampleClass?

Answer Source

Yes it will since string is a reference type and your string Attribute is actually referring to SecondClass.HakunaMatata. BTW, your this line in SampleClass

Attribute = SampleClass.HakunaMatata;

Should be

Attribute = SecondClass.HakunaMatata;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download