When must we use extern alias keyword in C#?
Asked Answered
S

2

34

When must we use extern alias keyword in C#?

Steinman answered 27/2, 2010 at 12:13 Comment(0)
H
34

Basically you only really need it when you want to use two types with the same fully qualified name (same namespace, same type name) from different assemblies. You declare a different alias for each assembly, so you can then reference them via that alias.

Needless to say, you should try to avoid getting into that situation to start with :)

Heder answered 27/2, 2010 at 12:27 Comment(3)
Just to add - even after adding extern alias declaration at the top of the comsumer *.cs file,compiler by default doesn't look for the type I'm using(which is present in that assembly).Compiler's default behavior is always to search for classes and types in the current and referenced assemblies having global alias.I end up using a fully qualified type name starting with the extern alias name e.g. my extern alias declaration was extern alias WidgetsVendor1; and still I was writing code like var wid = new WidgetsVendor1.Widgets.Widget();.I can't simply do-var wid = new Widgets.Widget();Breadnut
@RBT: No, it only declares the alias. But you could then have using WidgetsVendor1.Widgets; and write var wid = new Widget();.Heder
ohh. Interesting! I didn't know that. I posted my comments based on my observation I had in the morning. Good to know that. I'm able to import the namespaces inside the extern alias using the using keyword. Thanks.Breadnut
D
33

It's there to help you hoist yourself out of a really deep hole dug by versioning. Say your first version of your program uses this class

using System;

namespace Acme.Financial.Banking {
  [Serializable]
  public class BankAccount {
    public double Balance { get; set; }
    //...
  }
}

And you've been serializing lots of bank accounts records with it. And an accountant starts complaining about the balance sheet being off by a billionth of a penny, so you change the class:

  public decimal Balance { get; set; }

Problem solved, the next customer has happy balance sheets. Until you're asked to upgrade an existing customer with lots of serialized records in the old format. Big problem, you cannot deserialize the records anymore since the class has changed.

extern alias solves your problem, you can reference both the old version and the new version of the class in your code, even though the namespace names and class names are the same.

Derail answered 27/2, 2010 at 14:10 Comment(1)
Very insightful use-case for using extern alias.Breadnut

© 2022 - 2024 — McMap. All rights reserved.