Thursday, February 11, 2010

Use an alias for a namespace or class

Use the using directive to create an alias for a long namespace or class. You can then use it anywhere you normally would have used that class or namespace. The using alias has a scope within the namespace you declare it in.
Sample code:
// Namespace:
using act = System.Runtime.Remoting.Activation;

// Class:
using list = System.Collections.ArrayList;
...
list l = new list(); // Creates an ArrayList
act.UrlAttribute obj; // Equivalent to System.Runtime.Remoting.Activation.UrlAttribute obj

Abstract class with non abstract methods

Can an abstract class have non-abstract methods?

An abstract class may contain both abstract and non-abstract methods.

But an interface can contain only abstract methods.

Ways to prevent a class from instantiated

Name two ways that you can prevent a class from being instantiated.
A class cannot be instantiated if it is abstract or if it has a private constructor.

Difference between override and new

This is all to do with polymorphism. When a virtual method is called on a reference, the actual type of the object that the reference refers to is used to decide which method implementation to use. When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class. For instance:
public class Base
{
public void Display()
{Console.WriteLine("Base Display");}
public virtual void SomeMethod()
{Console.WriteLine("virtual SomeMethod");}
public virtual void SomeOtherMethod()
{Console.WriteLine("virtual SomeOtherMethod");}
}
public class Derived : Base
{
public void Display()
{Console.WriteLine("Derived Display");}
public override void SomeMethod()
{Console.WriteLine("override SomeMethod");}
public new void SomeOtherMethod()
{Console.WriteLine("new SomeOtherMethod");}
}
will end up calling Derived.SomeMethod if that overrides Base.SomeMethod.Will first call Base.SomeOtherMethod , then Derived.SomeOtherMethod . They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the
base method.
If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).
static void Main(string[] args)
{
Base b1 = new Base();
b1.SomeMethod();
b1.Display();

Base b2 = new Derived();

b2.SomeMethod();
b2.Display();
Base b3 = new Derived();
b3.SomeOtherMethod();
Derived d = new Derived();
d.SomeOtherMethod();
}
Output
virtual SomeMethod
Base Display
override SomeMethod
Base Display
virtual SomeOtherMethod
new SomeOtherMethod