C# Object Creation General Question

G

Guest

I have a general question regarding this piece of code that I wrote. This
works fine, however I am confused as to how I am able to pull the sb instance
out at the end? When I create the XmlTextWriter class and pass it in sw
(which in turn sw was created with sb) how is the sb object being maintained
and populated via the writer instance? My initial thought was that only
writer would contain the string....but to my surprise the sb instance
contained the string? how, why? How is sb being built? My goal is to
understand this concept so I can develop similar functionality in my classes.


StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlTextWriter writer = new XmlTextWriter(sw);

writer.Formatting = Formatting.Indented;
writer.Indentation = 5;

writer.WriteStartDocument();
writer.WriteComment("XML Validation Request " + System.DateTime.Now);
writer.WriteStartElement("XmlValidationTicket");
writer.WriteStartElement("Request");
writer.WriteCData(fragment);
writer.WriteEndElement();
writer.WriteElementString("Status", status);
writer.WriteElementString("ErrorMessage", errorMsg);
writer.WriteEndElement();
writer.Close();

return sb.ToString();
 
M

Morten Wennevik

Hi Chris,

This isn't a very good explanation, but maybe it can shed some light.
writer transfers data to an object of your choice, so when you write to
it, it is in fact passing the data to the StringWriter, which in turn
passes it on to a StringBuilder.

sb is created in the first line, a reference to it is held by sw and a
reference to sw is held by writer.

public class A
{
public string Text;
}

public class B
{
private A a;
public B(A a)
{
this.a = a;
}

public void Write(string s)
{
a.Text += s;
}
}

public class C
{
private B b;
public C(B b)
{
this.b = b;
}

public WriteStuff(string s)
{
b.Write(s);
}
}

....

A a = new A();
B b = new B(a);
C c = new C(b);
c.WriteStuff("Hello World");

//a.Text == "Hello World"

The code is untested so there might be typos.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top