Question

I saw this C# using statement in a code example:

using StringFormat=System.Drawing.StringFormat;

What's that all about?

Was it helpful?

Solution

That's aliasing a typename to a shorter name. The same syntax can also be used for aliasing namespaces. See using directive.

(Updated in response to Richard)

OTHER TIPS

It's an alias, from now on, the user can use StringFormat to refer to System.Drawing.StringFormat. It's useful if you don't want to use the whole namespace (in case of name clash issues for example).

source: using Directive article from MSDN

Perhaps a different, unrelated StringFormat is declared in another namespace like Acme.Stuff. If that were the case, this would cause confusion:

using System.Drawing; // Contains StringFormat type.
using Acme.Stuff;  // Contains another StringFormat type.

private void Foo()
{
    StringFormat myFormat = new StringFormat(); // which one to use?
}

Aliasing is with using on the StringFormat=System.Drawing.StringFormat clears up some of the confusion.

This will define an alias to System.Drawing.StringFormat.

That's the same thing like this example:

using SQL = System.Data.SqlServer;

SQL.SqlConnection sql = new SQL.SqlConnection();

It means you're using StringFormat as an alias for System.Drawing.StringFormat;

It's a alias for the namespace

The using keyword is used for importing namespaces or aliasing classes or for managing scope on disposable objects. Here we are talking about the namespace usage.

using StringFormat=System.Drawing.StringFormat;

The way using was used here is a little unusual in C# but more common in Java import statements. What it does is provide a StringFormat alias without importing the entire System.Drawing namespace. Some people with a Java background like to proactvely import only the classes being used rather than whole anmespaces (aka Java packages). Arguably you proactively avoid potential name conflicts if you import only specific class names but it isn't very common in C# and Visual Studio doesn't encourage it the way, say, Netbeans does for Java.

The more common usuage of aliasing is to resolve class names to a shortened alias when there is a naming conflict.

using System.Drawing;
using AwesomeCompany.ReallyAwesomeStuff.AwesomeLibrary.Drawing;
/* AwesomeCompany.ReallyAwesomeStuff.AwesomeLibrary.Drawing has a StringFormat class */
using AwesomeStringFormat = AwesomeCompany.ReallyAwesomeStuff.AwesomeLibrary.Drawing.Stringformat;
using StringFormat = System.Drawing.StringFormat;

public class AwesomeForm() : Form
{
    private AwesomeForm()
    {
        AwesomeStringFormat stringFormat = new AwesomeStringFormat();
        stringFormat.Color = Color.Red;
        /* etc */
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top