RSS
Giga Web Solution - Gaetano Santonastaso

Questions every .NET developer should be able to answer

I was recently looking on stackoverflow about interview questions and I came across an article about what are the questions that every developer should know. Not all the questions had an answer so I decided to give it a try and answer all of them with some additional one I consider relevant.

The article in question is Questions every good .NET developer should be able to answer?.

Let's make a start....

What's the difference between an abstract class and interface?

An interface is a reference type containing only abstract members which are implicitly public. An interface doesn't contain constants, constructors, data fields, destructors, static members or other interfaces. It is simply an empty shell that define 'the contract'.....what the class that implements it can do.

An abstract class on the other hand can implement methods, fields,and properties. In other words it can define behaviour, it specifies what an object is.


What's the difference between overriding and overloading a method?

Overloading is when you have multiple methods in the same scope, with the same name but different signatures.

public void GetAnswer()
{
}

public void GetAnswer(string question)
{
}

Overriding allows to change the functionality of a method in a child class.

public class BaseClass
{
    public virtual void GetAnswer()
    {
        //Do something
    }
}

public class DerivedClass: BaseClass
{
    public virtual void GetAnswer()
    {
        //Do something else 
    }
}


What's the difference between protected and internal? What about "protected internal"?

From MSDN:

Protected:

The type or member can only be accessed by code in the same class or struct, or in a derived class.

Internal:

The type or member can be accessed by any code in the same assembly, but not from another assembly.

Protected internal:

The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.


What's the difference between a static method and a non-static method?

The main difference between a static method and a non static method(instance method) is that the first belongs to the class while the second belongs to an object of a class(instance of a class). Furthermore the static method can be called both on the class as well as an object of the class. A static method can access only static members while an instance method can access both static and non-static members. Finally yhe static method can be called without instantiating the class to which it belongs.


What are Extesnion Methods?

From MSDN Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

public static class MyExtensions
{
    public static int WordCount(this String str)
    {
        return str.Split(new char[] { ' ', '.', '?' }, 
                         StringSplitOptions.RemoveEmptyEntries).Length;
    }
}   

string s = "Hello Extension Methods";
int i = s.WordCount();


What does the "volatile" keyword in C# mean?

From MSDN The volatile keyword indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.


What's a weakreference? When would you want to use one?

From MSDN Aweak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist. When you use a weak reference, the application can still obtain a strong reference to the object, which prevents it from being collected. However, there is always the risk that the garbage collector will get to the object first before a strong reference is re-established. Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection.

 class Program
    {
        static void Main()
        {
            // Create a Car
            var firstCar = new Car("BMW");

       // Set weak reference
        var wr = new WeakReference(firstCar);

        //Now Remove any reference to the Car by making it null
        firstCar = null;

        if (wr.IsAlive)
        {
            Console.WriteLine("Car is still alive");
            var secondCar = wr.Target as Car;
            Console.WriteLine(secondCar.CarType);
            secondCar = null;
        }
        else
        {
            Console.WriteLine("firstCar is dead");
        }

        // Lets call the garbage collector
        GC.Collect();

        // At this point it should not be alive
        if (wr.IsAlive)
        {
            Console.WriteLine("Car is still alive");
        }
        else
        {
            Console.WriteLine("Car is dead");
        }

        Console.ReadLine();
    }

    public class Car
    {
        public readonly string CarType;

        public Car(string carType)
        {
            CarType = carType;
        }
    }

And the output is The output should be

firstCar is still alive

BMW

Car is dead


What are Generics

From MSDN Generics were introduced in .NET version 2.0 and allow to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations.


What is a Nullable types

From MSDN Nullable types are instances of the System.Nullable struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable can be assigned the values true false, or null.


Covariance and Contravariance

Covariance and Contravariance refers to the interchangeability between types from narrower to wider and vice.

Covariant: converting from wider (Animals) to narrower (Cats).

Contravariant: converting from narrower (Triangles) to wider (Shapes).

Invariant: Not able to convert.


What's the difference between a value-type and a reference type?

From MSDN The value types consist of two main categories:

Structs and Enumerations

Structs fall into these categories:

     Numeric types
     Integral types
     Floating-point types
     Decimal

bool

User defined structs.

Variables that are based on value types directly contain values. Assigning one value type variable to another copies the contained value. This differs from the assignment of reference type variables, which copies a reference to the object but not the object itself.

All value types are derived implicitly from the System.ValueType.

Unlike with reference types, you cannot derive a new type from a value type. However, like reference types, structs can implement interfaces.

Variables of reference types store references to the actual data. To declare reference types the following keywords are used:

class

interface

delegate

dynamic

object

string


What is Reflection?

Reflection is used to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. RIt allows managed code to read its own metadata to find assemblies, modules and type information at runtime.


What does the "readonly" keyword in C# mean?

From MSDN The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

Write your own linked list class without using the built-in classes. A Linked list is a list that contains two fields for a value, one which contains the stored data and one referencing the next value. Together these two fields build a node, which is an element inside the linked list.

        class Program
        {
            static void Main(string[] args)
            {
                // string linked List
                var stringLinkedList = new GenericsLinkedList(); 
                const string s1 = "Yes";
                const string s2 = "No";
                const string s3 = "True";
                const string s4 = "False";
                stringLinkedList.AddHead(s1);
                stringLinkedList.AddHead(s2);
                stringLinkedList.AddHead(s3);
                stringLinkedList.AddHead(s4);
                //display List
                foreach (var str in stringLinkedList)
                {
                    Console.WriteLine("----" + str);
                }

                //Integer LinkedList
                var integerList = new GenericsLinkedList();
                const int n1 = 1;
                const int n2 = 2;
                const int n3 = 3;

                integerList.AddHead(n1);
                integerList.AddHead(n2);
                integerList.AddHead(n3);

                foreach (var intger in integerList)
                {
                    Console.WriteLine("----" + intger);
                }

                Console.ReadKey();


            }
        }

        // Generic Linked List
        class GenericsLinkedList
        {
            private LinkedlistNode _head;
            public GenericsLinkedList()
            {
                _head = null;
            }

            public void AddHead(T t)
            {
                var node = new LinkedlistNode(t) { Next = _head };
                _head = node;
            }

            public IEnumerator GetEnumerator()
            {
                var current = _head;

                while (current != null)
                {
                    yield return current.Item;
                    current = current.Next;
                }
            }

            class LinkedlistNode
            {
                public LinkedlistNode Next { get; set; }
                public T Item              { get; private set; }

                public LinkedlistNode(T t)
                {
                    Next = null;
                    Item = t;
                }
            }
        }


What are HttpHandlers?

From MSDN An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser. ASP.NET offers a few default HTTP handlers:

Page Handler (.aspx): handles Web pages

User Control Handler (.ascx): handles Web user control pages

Web Service Handler (.asmx): handles Web service pages

Trace Handler (trace.axd): handles trace functionality

Typical scenarios for HTTP Handlers in ASP.NET are for example

delivery of dynamically created images (charts for example) or resized pictures.

RSS feeds which emit RSS-formated XML

For a comprehensive article look at Microsoft Support


What are HttpModules?

From MSDN An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.

For a comprehensive article look at Microsoft Support


What's the difference between Viewstate and Sessionstate?

View State Is stored into a hidden field and is specific to a particular web page. Session State contains information that is pertaining to a specific session (by a particular client/browser/machine) with the server. This allows to to track what the user is doing on the site across multiple pages.


How do short-circuited operators work?

Short-circuited operators such as ?? and || evaluate both boolean expression in a statement only if the first statement is true.

    //Both are evaluated
    if (_firstCondition =="" & _secondCondition == "")
    {
     //Some code 
    }

    // The second condition is evaluated only if the first is true
    if (_firstCondition =="" && _secondCondition == "")
    {
     //Some code 
    }


What's the difference between a left join and an inner join?

Left Join returns all of the records in the left table regardless if any of those records have a match in the right table as well as any matching records from the right table.

Inner Join returns all of the records in the left table that have a matching record in the right table.

For a comprehensive article look at Visual Representation of SQL Joins


Explain what the StringBuilder class is and why you'd want to use it?

The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. The String object on the other hand is immutable so every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object.


Explain what happens when you pass a "ref" or "out" parameter into a method. What's the difference between those two keywords?

The ref keyword tells the compiler that the object will be initialized before entering into the function, while out keyword tells the compiler that the object will be initialized inside the function.

ref is two-ways, out is out-only.








Aug5

Back To List