Archive

Archive for March, 2009

Escape invalid XML Chars

March 27th, 2009 No comments

When working with XML, you sometimes want to save some Text into the XML.
That can lead to problems when you use special Chars which then confuses the XML Parser.

To fix that you could just use multiple Replaces over your String or just use the .Net Function:
System.Security.SecurityElement.Escape

Example:

string myText = "Hello & World! <3";
string myTextXMLSafe = System.Security.SecurityElement.Escape(myText);
// myTextXMLSafe is now "Hello &amp; World! &lt;3"
Ad
Categories: C#, Programming Tags: ,

Anonymous Types and Generics

March 5th, 2009 No comments

C# 3.0 has a “nice” Feature called “Anonymous Types”.

Basically it is great for LINQ where you want to create a Type on the fly.
To create such a Type just use

var myAnonymousObject = new {
    Firstname = "John",
    Lastname = "Doe"
};

Now you possibly want to extend that a little and have a Function return a List of such a Type.
You can’t use List<T> because you don’t know the Type. You could use a List<object> but that’s not nice. It’s better to use a Feature called “Casting by Example”.

An Example Function implementing this Feature could look like:

public List<T> GetList<T>(T exampleObject)
{
    List<T> newList = new List<T>();
    // TODO: Fill the List somehow
    return newList;
}

You can then call this Function like this:

var someList = GetList(
    new {
        Firstname = "",
        Lastname = ""
    }
);
Ad