.NET job interview questions.

  1. Why it is bad practice to use virtual method inside the constructor?

    When you make a virtual method call in a constructor, and it is not the most derived type in its inheritance hierarchy, that it will be called on a class whose constructor has not been run, and therefore may not be in a suitable state to have that method called. For example:

    class Parent
    {
        public Parent()
        {
            DoSomething();
        }
        protected virtual void DoSomething() {}
    }
    
    class Child : Parent
    {
        private string foo;
        public Child() { foo = "HELLO"; }
        protected override void DoSomething()
        {
            Console.WriteLine(foo.ToLower());
        }
    }
    

    NullReferenceException will be thrown, because An object’s base constructor is called before its own constructor. By having a virtual call in an object’s constructor you are introducing the possibility that inheriting objects will execute code before they have been fully initialized.

  2. What is the difference between finalize and dispose in .NET?

    Finalizers are run by the Garbage Collection before an object that is eligible for collection is reclaimed. Dispose() is meant for cleaning up unmanaged resources, like network connections, files, handles to OS stuff, &c. It works best in conjunction with the using block where the compiler makes sure that Dispose() will be called immediately once you are done with an object – and also ensures that you cannot work with the object anymore once it’s disposed.

    Destructor implicitly calls the Finalize method, they are technically same. Dispose is available with those object which implements IDisposable interface.
    The programmer has no control over when the destructor is called because this is determined by the garbage collector.

    Dispose must be called explicitly on a type which implement IDisposable. It can be called either through the Dispose() method itself or via the using construct. The GC will not call Dispose automatically.

    A finalizer or destructor (as the language specification calls it) on the other hand will automatically be called sometime after the object was eligible for cleanup. Finalize methods are executed sequentially on a dedicated thread.

Share this post:Tweet about this on TwitterShare on Facebook0Share on LinkedIn0Share on Google+0Share on Reddit0Email this to someoneDigg this