what are sealed methods?

  • sealed keyword can be used at the class level and a method level
  • using a sealed keyword on a method restricts the method from being overriden by any sub classes
  • It is used in cases when the method is already extended enough and any further extension is not desired.
class A
    {
        public virtual int Add()
        {
            Console.WriteLine("A.Add()");
            return 5 + 4;
        }
    }

    class B : A
    {
        public sealed override int Add()
        {
            Console.WriteLine("B.Add()");
            return 7 + 3;
        }
    }

    class C : B
    {
        // throws a compilation error here
        // 'C.Add()': cannot override inherited 
        // member 'B.Add()' because it is sealed
        public override int Add() 
        {
            Console.WriteLine("C.Add()");
            return 99 + 1;
        }
    }

How can you maintain the Uniqueness of a Key in a Dictionary()?

  • Technically a Dictionary requires its Keys to be unique.
  • Dictionary also uses Hashing on the Keys to ensure access to a particular key can happen in constant time.
  • If there is a complex Type (such as a custom class) we can override the GetHashCode() and Equals() method which the Dictionary internally uses to set the Key, and how two Keys can be compared while lookup.

Can you add a ComplexType as a Key in a Dictionary<T, int>()?

Can you add a ComplexType as a Key in a Dictionary()?

Yes. Technically it is possible. As long as the object references that are passed to the keys of the dictionary are not equal (meaning they're new instances of the type T), a dictionary can accept them without any exception.


class A
{
  public virtual int Add()
  {
    return 5 + 4;
  }
}
    
Dictionary<A, int> dict = new Dictionary<A, int>();
for (int i = 0; i < 10; i++)
{
    dict.Add(new A(), i);
}

foreach (var kv in dict)
{
    Console.WriteLine($"{kv.Key} => {kv.Value}");
}

What is the difference between Extension methods and a Decorator

Although both Decorator and Extension method try to extend the functionality of an existing component without having to modify it, the way they do is different.

  • A decorator wraps an existing functionality to enhance a new functionality,
  • An extension method is syntactical sugar to a static method that is extended over an existing type.

If we don’t use an IDisposable in a using block, will the Dispose method be called?

The answer is No. The Dispose method is invoked by the runtime only when the class that implements the IDisposable interface is initialized with a static block setup.

class MyClass : IDisposable 
{
  public void Dispose()
  {
     Console.WriteLine("Calling MyClass.Dispose");
  }
}

MyClass c = new MyClass();
using(MyClass uc = new MyClass()) {}

output:
Calling MyClass.Dispose  //printed only once