Jul 23
Multiline string literals in c#
icon1 sam sinfield | icon2 CSharp | icon4 07 23rd, 2007| icon33 Comments »

Having programmed in Python for the last year and now moving over to csharp, one of the things that irritated me about csharp was how it handled strings.

For example, in python, assigning a comma seperated object representation to a string variable would simply be:

var = “%s,%s,%s”%(obj1,ob2,ob3)

whereas in c#, it would be:

var = obj1.ToString()+”,”+obj2.ToString()+”,”+obj3.ToString()

This still pisses me off and I still haven’t found a more elegant way to do it and it’s only basic stuff.

The other is multiline strings.

eg, a multiline in python would simply be

var = “”"this is

a

multiline string”"”

in c#, until now, I’ve been using the longwinded way of:

var = “this is \n”

+”a \n”

+”multiline string”"
Until I’ve now discovered you can do it like:

var = @”this is
a
multiline string”

Wow, you learn something new everyday, how could I have not known this before, something so basic. I still prefer to code python and some things in c# and the .NET Framework really bug me but things are getting better

Apr 11

I’ve been really slow in making a first post but I thought I would post this code snippet as it seems to be something I’m using quite a lot at the moment. It is for building xml from a database:

System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
xmldoc.LoadXml("");
System.Xml.XmlElement root = xmldoc.DocumentElement;
try
{
SqlConnection conn = new SqlConnection(connectionstring);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlSelectStatement;
using (SqlDataReader dr = cmd.ExecuteReader())
{
// Process rows
while (dr.Read())
{
System.Xml.XmlElement row = xmldoc.CreateElement("row");
for(int i=0;i
{
System.Xml.XmlElement el = xmldoc.CreateElement(dr.GetName(i));
if(!dr.IsDBNull(i))
{
el.InnerText = dr.GetValue(i).ToString();
}
row.AppendChild(el);
}
root.AppendChild(row);
}
}
conn.Close();
}
catch(){}

There is another way of doing it directly into xml using cmd.ExecuteXmlReader and putting ” for xml auto” on the end of your sql select statement but apparently this only works in sqlserver 200 or higher and it puts all the fields as attributes of a node with the name of the table and no root node which I didn’t like, personal choice.

I’m sure this has its problems, let me know you think