Tag Archive: c#

Verbatim Identifiers and verbatim string literals in C#

Browsing through some of my old answers on StackOverflow, I came across this question I had answered regarding verbatim identifiers in the C# language. I want to take a moment to talk about this mysterious language feature, because it actually has multiple usages, one which is quite common, and you just might not be aware you are using it.

To start, I’ll describe to you what a verbatim identifier actually is by citing the C# language specification.

The prefix “@” enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character @ is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an @ prefix is called a verbatim identifier. Use of the @ prefix for identifiers that are not keywords is permitted, but strongly discouraged as a matter of style.

This text comes from section 2.4.2 of the language specification. It is also interesting to note that this language feature has been available since the first version of C#, specifically version 1.0 and 1.2, but it is not a feature that you would normally seek out as you learn a language. Good programmers generally try to find better names for variables than ‘object’ or ‘string’, especially since they conflict with existing type identifiers.

A valid usage of this language feature would be the following.

public string ToString(object @object)
{
    string @string = @object as string;

    if (@string != null)
        return @string;

    throw new ArgumentException("@object is not of type System.String.");
}

This is a terrible piece of code, but it does demonstrate the usage of the language feature correctly. But the language feature itself is a bit more flexible than that, but I don’t believe by design. We would of course have to ask the language designers, but let’s look at the code from the question I answered on StackOverflow.

_scale_id_regex = @ConfigurationSettings.AppSettings["some_setting"];

The gentlemen asked what the purpose of this symbol was in this piece of code. What I described earlier is pretty much the extent of what is outlined by the language specification, but the short answer is that it does not serve any real purpose. It is simply allowed by the language rules, and thus allowed by the compiler implementation. You can look at it a bit deeper however. Almost everything in code that has a name is considered an identifier, in this case ConfigurationSettings is the identifier, and verbatim identifiers are allowed by the language rules.

You’re hopefully wondering by now what this has to do with string literals, aha! String literals. A string literal in C# is identified by the usage of @ at the beginning of zero or more characters enclosed in double quotes, as in @"The fox jumped over the hole.". Again, we should reference the C# language specification to describe a string literal.

A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escaped-sequence. In particular, simple escape sequences, and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.

We never really think about verbatim identifiers, and we don’t think about string literals as verbatim string literals as programmers. We just think of string literals, because that is the common terminology, but the usage of the @ symbol to specify something as verbatim dates back to C# 1.0 and 1.2 with verbatim identifiers and string literals. The language feature is still very much alive into C# 5.0 and while verbatim identifier usage is very rare (and should be), verbatim string literals are a daily routine for programmers.

Why I think Microsoft shouldn’t make observable properties part of the C# Language specification.

INotifyPropertyChanged, how I love you implement you in every object over and over. How I can’t make you a reusable base class because it causes me to break important inheritance hierarchies. I love it, but I hate it because it is one of the most repetitive things I do in programming. It’s absolutely vital for data-binding in various frameworks like Windows Forms and Windows Presentation Foundation, but I can’t help but think “why isn’t this a core part of the C# language?”.

My solution would to be to add a contextual keyword to the C# language specification, and call it observable. It would be used like this.

public observable class A
{
    public observable String PropertyName
    {
        get;
        set;
    }
}

And this is what I see the compiler generating.

public class A : INotifyPropertyChanged
{
    public String PropertyName
    {
        get
        {
            return propertyNameField;
        }
        set
        {
            propertyNameField = value;
            OnNotifyPropertyChanged("PropertyName");
        }
    }

    public PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

How this should work is that when you compile your class, the compiler sees the observable keyword on the class and implements INotifyPropertyChanged interface for the class. Next, it sees any properties that are also observable and injects a call to OnPropertyChanged with the appropriate parameters. Okay, so this is a pretty good argument for implementing this, but that isn’t the title of my post.

The problem with this, albeit requested or thought of by many programmers over the years, is you have zero control over this. I’ll list out some of the limitations.

  • You can’t put a lock in OnPropertyChanged(String)
  • You can’t put any custom code in OnPropertyChanged(String)
  • You can’t use this with .NET 4.5 caller attributes
  • You can’t control the accessibility of OnPropertyChanged(String)
  • You can’t control whether OnPropertyChanged(String)
  • can be overridden or not.

In general, this is a bad idea. You could potentially solve all of these problems with compiler flags, but I believe this creates language and compiler bloat, both of which I disagree with. I’m sure the C# language team has already visited this discussion, Anders himself has discussed it at one point. I think the real solution would be to think outside of the box and how to ease-the-pain of implementing the interface instead.

A PropertyHelper class for property setter validation.

A common practice is to do property-level validation in the property setter of an object like the following.

public String Name {
    get {
        return this.name;
    }
    set {
        if (value == null) {
            throw new System.ArgumentNullException("value");
        }
        if (value.Length == 0) {
            throw new System.ArgumentException("Name cannot be empty.", "value");
        }
        this.name = value;
    }
}

Most of the time though, this violates the DRY principle (Don’t Repeat Yourself), because you may need to do the same exact validation in a constructor for example.

public Customer(String name) {
    get {
        return this.name;
    }
    set {
        if (name == null) {
            throw new System.ArgumentNullException("name");
        }
        if (name.Length == 0) {
            throw new System.ArgumentException("Name cannot be empty.", "name");
        }
        this.name = value;
    }
}

Now you might be asking at this point, “Why are you not just using the Name property in the constructor, which would invoke the setter validation?”. Often times when writing POCO’s for Entity Framework, you will use virtual properties to enable proxy creation. Calling into a virtual property is a Microsoft Usage violation (CA2214:DoNotCallOverridableMethodsInConstructors), because if the property is overridden and the deriver does not call the base property, your setter is not invoked and your validation is ignored.

I started thinking, and I came up with an interesting idea to use a helper class with a fluent-api to do validation. Usually when I come up with ideas, I write code how I would like to write it, and then implement the API based on how I want it to look. I wrote this psuedo code.

public String Name {
    get {
        return this.name;
    }
    set {
        PropertyHelper.Validate<String>("Name", value)
            .ArgumentNullException()
            .ArgumentException(v => v.Length == 0)
            .ArgumentOutOfRangeException(v => v.Length > 32);
        this.name = value;
    }
}

Next, I started to actually write the implementation, which obviously had to start with PropertyHelper.

internal static class PropertyHelper
{
    internal static ? Validate<T>(String propertyName, T value) {
        ?
    }
}

At this point I was thinking about how a fluent-api is actually designed, and I had to figure out the following:

  • What does Validate<T> return?
  • How do I pass the property name and value correctly so it is known for each API call?

To solve these I answered each. First, each ‘fluent-api’ will really be a type of exception that can be thrown by some condition that represents the validation rule. Secondly, I would need to provide the property name and value to it, and it would have to provide that to the next call. I came up with this.

internal class PropertySetter<T>
{
    private string propertyName;
    private T value;

    public PropertySetter(String propertyName, T value) {
        this.propertyName = propertyName;
        this.value = value;
    }
}

This completes the two key questions in the prior method I wrote for PropertyHelper.

internal static class PropertyHelper
{
    internal static PropertySetter<T> Validate<T>(String propertyName, T value) {
        return new PropertySetter<T>(propertyName, value);
    }
}

Now I needed to write the actual exception-api’s, so I started with the most simple ArgumentNullException.

internal static class PropertyHelper
{
    internal static PropertySetter<T> Validate<T>(String propertyName, T value) {
        return new PropertySetter<T>(propertyName, value);
    }

    internal static PropertySetter<T> ArgumentNullException(Func<T, Boolean> predicate) {
        if (!predicate(value)) {
            throw new System.ArgumentNullException(propertyName);
        }
        else {
            return this;
        }
    }
}

This works well also. Each time a call is made to ArgumentNullException(), it will return itself to the caller, thus passing the property name and value along with it. The predicate is just a simple anonymous function that takes T which is the type of the value. This is the same predicate that is used for SingleOrDefault(Func<T, Boolean>) that is used with IEnumerable. Next, I can implement a few more methods.

internal static class PropertyHelper
{
    internal static PropertySetter<T> Validate<T>(String propertyName, T value) {
        return new PropertySetter<T>(propertyName, value);
    }

    internal static PropertySetter<T> ArgumentNullException(Func<T, Boolean> predicate) {
        if (!predicate(value)) {
            throw new System.ArgumentNullException(propertyName);
        }
        else {
            return this;
        }
    }

    internal static PropertySetter<T> ArgumentException(Func<T, Boolean> predicate, String message) {
        if (!predicate(value)) {
            throw new System.ArgumentException(message, propertyName);
        }
        else {
            return this;
        }
    }
}

Because each one returns a PropertySetter<T> you can keep chaining them, and you can chain them in the order you want. Whichever predicate returns false first will throw that exception.

public Int32 Value {
    get {
        return this.value;
    }
    set {
        PropertyHelper
            .Validate<Int32>("Value", value)
            .ArgumentException(v => v == 1, "Value cannot be 1.");
        this.value = value;
    }
}

There is still some level of DRY here, but it is a lot cleaner and easier to maintain. It also allows you to abstract away the logic that throws the exceptions and checks the predicate, allowing you to write code that visibly focuses on the validation itself. Although I called it PropertyHelper, you could really use this almost anywhere. Properties, methods, and constructors. This also isn’t the best approach probably, but it was an interesting approach and a fun one to write. You can grab the full implementation below.

//-----------------------------------------------------------------------------
// <copyright file="PropertyHelper.cs" company="DCOM Productions">
//     Copyright (c) DCOM Productions.  All rights reserved.
//     Open Source. Personal and Commercial usage allowed.
// </copyright>
//-----------------------------------------------------------------------------

namespace Northwind.Data
{
    using System;
    using System.Globalization;
    using System.Linq;

    /// <devdoc>
    /// Helper methods for property setters.
    /// </devdoc>
    public static class PropertyHelper
    {
        /// <summary>
        /// Performs property validation for the property setter.
        /// </summary>
        /// <typeparam name="T">The type of property value.</typeparam>
        public static PropertySetter<T> Validate<T>(String propertyName, T value) {
            return new PropertySetter<T>(propertyName, value);
        }
    }

    /// <summary>
    /// Provides methods for the SetValue() method of a property.
    /// </summary>
    /// <typeparam name="T">The type of property value.</typeparam>
    public class PropertySetter<T>
    {
        private string propertyName;
        private T value;

        /// <summary>
        /// Initializes a new instance of the FaultTrack.Data.PropertyHelper class.
        /// </summary>
        public PropertySetter(String propertyName, T value) {
            this.propertyName = propertyName;
            this.value = value;
        }

        /// <summary>
        /// Throws a System.ArgumentNullException if the property value is null.
        /// </summary>
        public PropertySetter<T> ArgumentNullException() {
            if (value == null)
                throw new System.ArgumentNullException(propertyName);
            else
                return this;
        }

        /// <summary>
        /// Throws a System.ArgumentException if the property value causes the specified predicate to return false.
        /// </summary>
        public PropertySetter<T> ArgumentException(Func<T,bool> predicate, String message) {
            if (!predicate(value))
                throw new System.ArgumentException(message, propertyName);
            else
                return this;
        }

        /// <summary>
        /// Throws a System.ArgumentOutOfRangeException if the property value causes the specified predicate to return false.
        /// </summary>
        public PropertySetter<T> ArgumentOutOfRangeException(Func<T,bool> predicate, String message) {
            if (!predicate(value))
                throw new System.ArgumentOutOfRangeException(propertyName, message);
            else
                return this;
        }
    }
}

ZipFile class (System.IO.Compression.FileSystem)

I was excited that the base class library in .NET 4.5 now includes native support for working with Zip files, but in my excitement I overlooked System.IO.Compression.FileSystem. The name of the assembly is actually misleading, because the namespace is still just System.IO.Compression, and it only contains one type and that’s ZipFile. This is a separate assembly from System.IO.Compression.dll so you will need to add it as an additional reference.

The ZipFile class is actually static, but it contains some four methods for quickly creating and reading zip files.

ZipFile.CreateFromDirectory(String, String)
ZipFile.ExtractToDirectory(String, String)
ZipFile.Open(String, ZipArchiveMode)
ZipFile.OpenRead(String)

ZipFile.CreateFromDirectory(String, String) is useful for quickly archiving entire directories. I could backup my documents for instance.

ZipFile.CreateFromDirectory(@"c:\users\danderson\documents", @"c:\users\danderson\documents\backup.zip");

I could do the reverse to restore my documents.

ZipFile.ExtractToDirectory(@"c:\users\danderson\documents\backup.zip", @"c:\users\danderson\documents");

There are some limitations however. One is that these methods will throw exceptions if the target path already exists when creating an archive, or a target directory exists when extracting files. If an exception is thrown, it will remain partially extracted however many files and folders were previously successful.

Base Class Library finally has first class support for zip archives in .NET 4.5

I’m very excited about this. First off, I hate third-party dependencies. I always try to accomplish everything with the platform I use, in this case the BCL. A friend of mine was asking me to write a blog article on System.IO.Packaging and how to use types like GZipStream. After suggesting SharpZipLib and DotNetZip, I became a rather curious rhino and did a quick Object Browser search in the .NET 4.5 base class library for the term zip. Sure enough, my eyes did not deceive me and I immediately saw ZipArchive! You will need to add a reference to System.IO.Compression.dll to use these types.

Immediately I began to just experiment with the type. After I wrote my own code on how I figured it would be used, I checked Msdn and sure enough my code was virtually identical to the example code.

namespace ZipArchiveDemo
{
    using System;
    using System.IO;
    using System.IO.Compression;
    using System.Linq;

    class Program
    {
        static void Main(string[] args) {
            const string path = @"c:\users\danderson\my documents\archive.zip";

            using (FileStream fstream = new FileStream(path, FileMode.Create))
            using (ZipArchive archive = new ZipArchive(fstream, ZipArchiveMode.Create)) 
            {
                ZipArchiveEntry entry = archive.CreateEntry("test.txt");
                
                using (StreamWriter writer = new StreamWriter(entry.Open())) {
                    writer.WriteLine("I'm just a curious little rhino!");
                }
            }

            if (!File.Exists(path)) {
                throw new System.IO.FileNotFoundException(String.Format("{0} was not found.", path));
            }

            using (FileStream fstream = new FileStream(path, FileMode.Open))
            using (ZipArchive archive = new ZipArchive(fstream, ZipArchiveMode.Read)) 
            {
                ZipArchiveEntry entry = archive.Entries.FirstOrDefault();

                using (StreamReader reader = new StreamReader(entry.Open())) {
                    Console.WriteLine(entry.Name);
                    Console.WriteLine(reader.ReadToEnd());
                }
            }

            Console.ReadKey();
        }
    }
}

Pretty simple and not much else to it. The first two using blocks create the archive and then I just do a quick check if it was created, and throw an Exception otherwise. The last set opens the archive and grabs the first entry (since there’s only one) and writes it to the standard output stream.

I have to hand it to the BCL team on this one. THANK YOU.

IValueConverter Interface (System.Windows.Data.IValueConverter)

Probably the most common question I get from people new to WPF is how to bind the Visibility of a control based on a System.Boolean value. WPF provides IValueConverter in System.Windows.Data specifically for converting one type to another and back when binding. Let’s setup a very simple example.

/// <summary>
/// ViewModel for MainWindow
/// Assigned to MainWindow.DataContext in its class constructor
/// </summary>
internal class MainWindowDataContext : INotifyPropertyChanged
{
    private bool _visible;

    public bool Visible {
        get {
            return _visible;
        }
        set {
            _visible = value;

            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null) {
                handler(this, new PropertyChangedEventArgs("Visible"));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Visibility="{Binding Visible}" />
    </Grid>
</Window>

You should already know that line 7 doesn’t work. There isn’t a conversion from System.Boolean to System.Windows.Visibility. This is where IValueConverter comes in, so we will make a new class that implements the interface and call it BoolToVisibilityConverter.

internal class BoolToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        if (!(value is bool)) {
            throw new System.ArgumentException("value is not of type System.Boolean", "value");
        }
        return (bool)value ? Visibility.Visible : Visibility.Hidden;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        if (!(value is Visibility)) {
            throw new System.ArgumentException("value is not of type System.Windows.Visibility", "value");
        }
        switch ((Visibility)value) {
            case Visibility.Visible:
                return true;
            default:
                return false;
        }
    }
}

The implementation is simple. When the binding gets the value from MainWindow.DataContext (eg. MainWindowDataContext.Visible) it is passed to the value parameter of object Convert. Then it’s up to the convert method to return the appropriate value based on the parameter. In this case, we do a simple check to make sure the parameter is in fact a System.Boolean value, and if it is we return the appropriate Visibility enumeration value. Obviously, ConvertBack does exactly the opposite when the value of the binding is set, and is propagated down to the data context. It takes a Visibility value and converts it to a System.Boolean value, which is assigned to MainWindowDataContext.Visible.

Now we need to update our Xaml to use the converter. This is done by including it as a resource and specifying the Converter attribute on the binding.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Resources>
            <local:BoolToVisibilityConverter x:Key="BoolToVisibilityConverterResourceKey"/>
        </Grid.Resources>
        <Button Visibility="{Binding Visible, Converter={StaticResource BoolToVisibilityConverterResourceKey}}" />
    </Grid>
</Window>

You can implement IValueConverter any time you need to convert one type to another and back in a binding.

Persistence Ignorant Architecture with Entity Framework ORM.

I finished the screencast and have uploaded it to YouTube here. I also have attached the source code to this blog post, but I wanted to comment on a few post-video changes I have made.

providerConnectionString = String.Empty;

if (String.IsNullOrWhiteSpace(providerConnectionString)) {
    throw new System.NotImplementedException(Properties.Resources.ConnectionStringNotSet);
}

I removed App.config from the project (which was never needed). You will need to set the connection string yourself, and I added the code to throw an exception with a reminder in case you forget. You should be able to use the Create Database from Model feature in the Entity Designer, but I was having troubles in the screencast so I created the tables manually.

Screencast Demo Code
Visual Studio 2010
Download PI-Entity-Demo.zip

Empty Pattern

This thread on Msdn was one I came across, and I felt it needed a much better answer. His question in short, is what is the difference between null, Empty, and “” in C#. I assume that you know what null and "" are, so I’m going to focus on the meat of the question. So the obvious question is what is Empty? Let’s look deeper into some existing types that use this pattern.

System.String
String value = String.Empty;

System.Drawing.Rectangle
Rectangle value = Rectangle.Empty

I could go on, but I will stop there. There are a few things that types using this pattern have in common.

  • They are types that have value semantics
  • Empty is a public static readonly field
  • Empty’s type is the same as its containing type

Okay.. but what does all this mean. Empty is a public static readonly field that represents the default value for an instantiated type that has value semantics. This pattern is useful for two reasons. One, for value types, because value types are not nullable, it is an easy way to have access to the default value of that type, and is equivelent to calling default(T). And secondly, it is useful to find out if an instance of a type has been modified from its default value. Let’s take a deeper look at how this pattern applies to Value Types and Reference Types, and we’ll start with a value type.

public struct Point {
    public static readonly Point Empty = default(Point);
    public int X { get; set; } 
    public int Y { get; set; } 
}

For value types, since they cannot be null, it is good practice to use default(T) for declaring the empty field, however new Point() works just as well. Remember that default(T) for structs will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullable, which is initialized like any struct.

Point p1 = Point.Empty;    // {0,0}
Point p2 = new Point();    // {0,0}
Point p3 = default(Point); // {0,0}

All three lines of code are equivelent, except in regards to performance. Using Point.Empty we are not instantiating a new instance of Point, but the other two methods do. A minor detail, but important to note regardless.

Point p = Point.Empty;
p.X = 1;
p.Y = 1;

if (p != Point.Empty) {
    p.X = 0;
    p.Y = 0;
}

Now you can see how Empty is useful. Very easy to see if the point has been modified from its default value. We can see how useful this pattern is for structures, and how its used in existing types in .NET. What about reference types? The same practices apply, but there is a difference in how we should declare the static field, because reference types can be null, which is their default value.

public class Point {
    public static readonly Point Empty = new Point();
    public int X { get; set; } 
    public int Y { get; set; } 
}

In the above sample, we changed our Point from a value type to a reference type, but note line two. Instead of using default(T), we are using new Point(). This is because the default value for a reference type is null, which is great, but we don’t want the default value, we want its Empty value.

The next important change, is that we must make the type immutable. Using this pattern on a mutable reference type will have negative impact and wrong behaviors in your application. Remember that value types use copy semantics, reference types hold a reference to the underlying object in memory, so if we were to use the following code:

Point p = Point.Empty;
p.X = 2;

This would actually modify the value of Point.Empty to be {2,0}. For this pattern to be viable when using a reference type, it must be immutable.

public class Point {
    public Point(int x, int y) {
        X = x;
        Y = y;
    }
    public static readonly Point Empty = new Point();
    public int X { get; private set; } 
    public int Y { get; private set; } 
}

There’s not much else to say, hopefully by now you understand why this pattern exists, so let’s recap my DO’s and DO NOT’s for this pattern.

DO Implement an T.Empty field on types that have value semantics.
DO Make T.Empty public static readonly.
DO Use default(T) as the value for T.Empty when used with a struct.
DO NOT Use default(T) as the value for T.Empty when used with a class, use new T() instead.
DO NOT Use this pattern on mutable reference types. Use them on immutable reference types like System.String.
DO NOT Use this pattern on types where value semantics don’t make sense.