Friday, February 15, 2013

Describe the difference between a Thread and a Process? Write an example to create both. (C#)

Threads vs Processes

A thread is analogous to the operating system process in which your application runs. Just as processes run in parallel on a computer, threads run in parallel within a single process. Processes are fully isolated from each other; threads have just a limited degree of isolation. In particular, threads share (heap) memory with other threads running in the same application. This, in part, is why threading is useful: one thread can fetch data in the background, for instance, while another thread can display the data as it arrives.

A great tutorial on threads and its implementations is :
http://www.albahari.com/threading/

What is an interface? When would you use an interface vs. an abstract class? (C#)

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:


Feature Interface Abstract Class
Multiple inheritance A class may inherit several interfaces. A class may inherit only one abstract class.
Default implementation An interface cannot provide any code, just the signature. An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modifiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface. An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity If various implementations only share method signatures then it is better to use Interfaces If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
Speed Requires more time to find the actual method in the corresponding classes. Fast.
Adding functionality (Versioning) If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constraints defined

Tuesday, February 12, 2013

What are satellite assemblies? (C#)

A satellite assembly is a .NET Framework assembly containing resources specific to a given language. Using satellite assemblies, you can place resources for different languages in different assemblies, and the correct assembly is loaded into memory only if the user selects to view the application in that language.

A good example of Satellite assembly implementation can be found here :
http://www.codeproject.com/Articles/352105/Satellite-Assembly-Example-in-Csharp-Step-by-Step

Is string a value type or a reference type?What are immutable objects in C#? (C#)

String is a reference type.
An object is immutable if its state doesn’t change once the object has been created. Consequently, a class is immutable if its instances are immutable.
There is one famous immutable class: System.String. When you think that you are modifying a string, you actually create a new string object.
Doing so comes at the cost of creating multiple string objects in memory when doing some intensive string computation. In this case you need to use the System.Text.StringBuilder class that provides a safe way to work with mutable string.

Boxing and Unboxing (C#)

Boxing is the operation of converting a value of a value type into a value of a corresponding reference type. Boxing in C# is implicit.

Unboxing is the operation of converting a value of a reference type (previously boxed) into a value of a value type. Unboxing in C# requires an explicit type cast. A boxed object of type T can only be unboxed to a T (or a nullable T).

Example:

int foo = 42; // Value type.
object bar = foo; // foo is boxed to bar.
int foo2 = (int)bar; // Unboxed back to value type.

Monday, February 11, 2013

Value types and Reference types in .Net (C#)

In .NET, there are two categories of types, reference types and value types.
Structs are value types and classes are reference types.
The general difference is that a reference type lives on the heap, and a value type lives inline, that is, where ever it is your variable or field is defined.
A variable containing a value type contains the entire value type value. For a struct, that means that the variable contains the entire struct, with all its fields.
A variable containing a reference type contains a pointer, or a reference to somewhere else in memory where the actual value resides.
This has one benefit, to begin with:
•value types always contains a value
•reference types can contain a null-reference, meaning that they don't refer to anything at all at the moment

Internally, reference types are implemented as pointers, and knowing that, and knowing how variable assignment works, there are other behavioral patterns:
•copying the contents of a value type variable into another variable, copies the entire contents into the new variable, making the two distinct. In other words, after the copy, changes to one won't affect the other
•copying the contents of a reference type variable into another variable, copies the reference, which means you now have two references to the same somewhere else storage of the actual data. In other words, after the copy, changing the data in one reference will appear to affect the other as well, but only because you're really just looking at the same data both places

When you declare variables or fields, here's how the two types differ:
•variable: value type lives on the stack, reference type lives on the stack as a pointer to somewhere in heap memory where the actual memory lives
•class/struct-field: value type lives inside the class, reference type lives inside the class as a pointer to somewhere in heap memory where the actual memory lives.

What is the difference between a struct and a class? (C#)

Classes Only:
•Can support inheritance
•Are reference (pointer) types
•The reference can be null
•Have memory overhead per new instance

Structs Only:
•Cannot support inheritance
•Are value types
•Are passed by value (like integers)
•Cannot have a null reference (unless Nullable is used)
•Do not have a memory overhead per new instance - unless 'boxed'

Both Classes and Structs:
•Are compound data types typically used to contain a few variables that have some logical relationship
•Can contain methods and events
•Can support interfaces

Can you overload a C# method by just changing its return type? If no, then why not? (C#)

Overloading is what happens when you have two methods with the same name but different signatures. At compile time, the compiler works out which one it's going to call, based on the compile time types of the arguments and the target of the method call.
For example :

string Substring (int startIndex)
string Substring (int startIndex, int length)

No, a C# method cannot be overloaded by only changing the return type. Overloading happens by changing the parameters. The return type of a method is not considered to be part of a method's signature (section 3.6), and an overload is determined before the compiler checks whether or not the return type will cause an error in the wider context of the method call. In other words, it's not part of the test for an applicable function member.

Sunday, February 10, 2013

How do you prevent a class from being inherited? Are there any such classes in the .NET framework? (C#)

In order to prevent a class in C# from being inherited, the keyword sealed is used. Thus a sealed class may not serve as a base class of any other class. It is also obvious that a sealed class cannot be an abstract class. Code below...
//C# Example
sealed class ClassA
{
public int x;
public int y;
}
No class can inherit from ClassA defined above. Instances of ClassA may be created and its members may then be accessed, but nothing like the code below is possible...
class DerivedClass : ClassA { } // Error

Sealed classed in .Net framework are : System.Drawing, System.Collections etc.

What is a Singleton and when is it used? Implement a singleton class. (C#)

A singleton is a class which only allows one instance of itself to be created - and gives simple, easy access to said instance. The singleton premise is a pattern across software development.
Details can be found here : http://csharpindepth.com/Articles/General/Singleton.aspx

Friday, February 8, 2013

What is a Disposable pattern? When do you use it? (C#)

A great blog already written about this : http://blog.nuclex-games.com/tutorials/idisposable-pattern/
Will add here if I learn anything new about the topic.

Tuesday, February 5, 2013

Remove duplicate words from a string (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Excercises
{
public class PhoneBook
{
Dictionary Unique = new Dictionary();
StringBuilder builder = new StringBuilder();
public void removeDups(string input)
{
//Split the string into words separated by a space (' ')
string[] myStr = input.Split(' ');
//traverse the array
for (int i =0;i (less than) myStr.Length; i++)
{
//if the word already exists as a key in the dictionary, just add the count other wise add the count as 1 and the key
if (Unique.ContainsKey(myStr[i]))
{
Unique[myStr[i]]++;
}
else
{
Unique.Add(myStr[i], 1);
}
}
//for every key in the dictionary, add that to the stringbuilder if the word is uniqie. If the word is not unique add only 1 key
foreach (var d in Unique)
{
if (d.Value == 1)
{
builder.Append(d.Key);
builder.Append(' ');
}
else
{
builder.Append(' ');
builder.Append(d.Key);
builder.Append(' ');
}
}
Console.WriteLine(builder.ToString());
}
}
class Program
{
static void Main(string[] args)
{
PhoneBook Book = new PhoneBook();
string str = "This is a test sentence for my test purposes only. I am a test resource";
Book.removeDups(str);
Console.ReadKey();
}
}
}

Hash Table versus Dictionary (C#)

What is the difference between a Hash Table and a Dictionary?

1. Hashtable is threadsafe and while Dictionary is not.
2. Dictionary is type safe which means that the values need not be boxed while Hashtable values need to be boxed or unboxed because it stores the values and keys as objects.
3. When you try to get the value of key which does not exists in the collection, the dictionary throws an exception of 'KeyNotFoundException' while hashtable returns null value.
4. When using large collection of key value pairs hashtable would be considered more efficient than dictionary.
5. When we retrieve the record in collection the hashtable does not maintain the order of entries while dictionary maintains the order of entries by which entries were added.
6. Dictionary relies on chaining whereas Hashtable relies on rehashing.

Write a program to build a simple phone book, with name and phone number – which one would you use for this?

A dictionary
public class PhoneBook
{
Dictionary Book = new Dictionary();
public void Entries()
{
Book.Add(12345, "Rishi");
Book.Add(23456, "Sarthak");
Book.Add(34567, "Bholu");

foreach (var s in Book)
{
Console.WriteLine("Name :{1}, Phone : {0}", s.Key, s.Value);
}
}
}

Monday, February 4, 2013

Pascal Triangle (C#)

Write a program to generate a Pascal triangle and print all the numbers on the 11th row

The Pascal triangle is represented in the diagram below :


public class Pascal
{
public void DrawTriangle(int n)
{
//validations
if (n == 0)
{
Console.WriteLine("Drawing pascal triangle");
Console.WriteLine(1);
}
else if (n == 1)
{
Console.WriteLine("Drawing pascal triangle");
Console.WriteLine(1);
Console.WriteLine(Environment.NewLine);
Console.WriteLine("{0},{1}", 1, 1);
}
else if (n < 0)
{
Console.WriteLine("Invalid row count!!");
}
//Implement the triangle
else
{
int[,] triangle = new int[n, n];
triangle[0, 0] = 1;
triangle[1, 0] = 1;
triangle[1, 1] = 1;
for (int i = 2; i < n; i++)
{
triangle[i, 0] = 1;
triangle[i, i] = 1;
for (int j = 1; j < n; j++)
{
triangle[i, j] = (triangle[i - 1, j - 1] + triangle[i - 1, j]);
}
}
for (int x = 0; x < triangle.GetLength(0); x++)
{
for (int y = 0; y < triangle.GetLength(1); y++)
{
if (triangle[x, y] != 0)
Console.Write(triangle[x, y] + " ");
}
Console.WriteLine();
}
}
}
}

Calling the method and printing the 11th row
static void Main(string[] args)
{
Pascal P = new Pascal();
P.DrawTriangle(11);
Console.ReadKey();
}

Sunday, February 3, 2013

All about LinkedLists

Implement a linkedList

//This is the data structure of a node of the linkedList

public class Node

{
public string Name;
public Node Next;
public Node()
{
Name = string.Empty;
Next = null;
}
}

The List!!
public class MyList
{
Node Head = new Node();
int size;
public MyList()
{
size = 0;
// Head = null;
}
//Find the Nth element from the tail
public Node Retrieve(int position)
{
Node temp = Head.next;
//validations
if (size == 0)
return null;
else if (position == 0)
return Head;
else if (position > size || position < 0)
throw new Exception();
else
{
while (temp.next != null)
{
Console.WriteLine(temp.data);
temp = temp.next;
}
Console.WriteLine(temp.data);
return temp;
}
}
Adding a node at the back
public void AddNodeAtBack(int data)
{
Node newNode = new Node();
newNode.data = data;
Node temp = Head.next;
if (size == 0)
{
Head.next = newNode;
size++;
}
else
{
while (temp.next != null)
{
temp = temp.next;
}
temp.next = newNode;
size++;
}
}
Adding a node in front public void AddNodeAtFront(int data)
{
Node newNode = new Node();
newNode.data = data;
//the validations
if (data == 0)
return;
else
{
if (size == 0)
{
Head.next = newNode;
size++;
}
else
{
newNode.next = Head.next;
Head.next = newNode;
size++;
}
}
}
Find the lenght of the linked list
public int Count()
{
return size;
}
Delete a node from a particular position
public void deleteNode(int pos)
{
Node temp = Head.next;
if (pos > size || pos < 0)
throw new Exception();
else
{
if (size == 0)
throw new InvalidOperationException();
else if (pos == 0)
{
//temp = null;
Head.next = temp.next;
temp = null;
size--;
}
else
{
{
for (int i = 1; i < pos - 1; i++)
{
temp = temp.next;
}
Node temp2 = temp.next;
temp.next = temp2.next;
temp2 = null;
size--;
}
}
}
}
}

Reverse the LinkedList
public void reverseWithoutArray()
{
Node Current = Head;
Node Start = Head.Next;
Node temp = Head.Next;
while (Start.Next != null)
{
temp = Start;
while (temp.Next.Next != null)
{
temp = temp.Next;
}
Current.Next = temp.Next;
temp.Next = null;
Current = Current.Next;
}
Current.Next = Start;
}
Print the nth (3rd) element from the tail of the list
Given an uni-directional linked list, detect infinite loop without using any extra data structure.
Sort the linked list