Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When must we use extern alias keyword in C#?

Tags:

c#

keyword

When must we use extern alias keyword in C#?

like image 870
masoud ramezani Avatar asked Feb 27 '10 12:02

masoud ramezani


People also ask

What is extern alias?

Each extern alias declaration introduces an additional root-level namespace that parallels (but does not lie within) the global namespace. Thus types from each assembly can be referred to without ambiguity by using their fully qualified name, rooted in the appropriate namespace-alias.

How to use alias in c#?

In the first use case, you define a scope, at the end of which an object is disposed. In the second use case, you create an alias for a namespace or import specific types from other namespaces. In the third use case, you import members of a single class with the static directive.


2 Answers

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 :)

like image 170
Jon Skeet Avatar answered Oct 02 '22 22:10

Jon Skeet


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.

like image 23
Hans Passant Avatar answered Oct 02 '22 22:10

Hans Passant