Copying strings in a less ugly way

So, for one reason or another, I was in a method that I had limited power to refactor. In this method there where two strings that, if certain conditions applied, needed to have the same value (Yeah, don’t get me started).

Let’s say it looked something like this:

s1 = "Hello";
s2 = "World";
s3 = "Hello Brave New World";

[...]
if(SomeCondition)
{
s1 = s3;
s2 = s3;
}
[...]

“So, what the hell can I do to make it less of an eyesore?”, I thought to myself.

After thinking about it, I came up with this:

private static (string, string) DuplicateString(string s)
{
    return (s, s);
}

And the end result looks like this instead:

s1 = "Hello";
s2 = "World";
s3 = "Hello Brave New World";

[...]
if(SomeCondition)
{
(s1, s2) = DuplicateString(s3);
}
[...]

Still not good, but a whole lot better!

Working with XML in C#

So, this is a post I’ve been meaning to write pretty much since I started the blog. In my adventures in programming I come across XML formats every now and then and I always forget how to create C# classes out of them. Instead of trying to find it on Google the next time, I’ll just read this post instead.

So, let’s say we have an XML file looking like this:

<?xml version="1.0" encoding="utf-8"?>
<Record>
<RecordArtist>Oasis</RecordArtist>
<RecordName>Be Here Now</RecordName>
<RecordYear>1997</RecordYear>
<RecordLabel>Creation Records</RecordLabel>
</Record>

Pretty simple structure, right? Let’s go through the motions of creating a class for this. First, you’ll need to convert the XML to XSD. Find the “Developer Command Prompt for VS 2019” and browse to where the above XML is located.

xsd.exe Record.xml

That’s it! Now you’ve got a XSD that can be used to create a C# class.
To create the class, go:

xsd.exe Record.xsd /c /n:RecordNamespace

Done! Use it in your project and you’re all set.

EDIT: A word of caution: You should always prefer having an XSD to start with instead of an XML. If the XML file doesn’t have all the fields they, naturally, won’t show up in the created class. But you already knew that.

Exceptions

I ran across a good post about exception handling here.

It got me thinking about my own way of handling exceptions in relation to what in the article is described as best practices (The term “best practices” is a bit of a rabbit hole in itself, but I’ll save that for another time).

Almost all of the things in the article I’m already doing or know about, but the thing that was most interesting was the part about decorating exceptions, – I had no idea that was a thing!

Most of the time, when debugging applications, I know from where the exception is being thrown but I wish I had some more context about it afterwards. This is where the decorating part can be quite handy. Keeping a mental note about that the next time I’m dealing with exceptions.