Both Method overloading and overriding are one of the strong features in object-oriented programming languages.

In a class when you have two methods performing similar functionality but they just require different signatures or types then you can overload them instead of giving them a new name. On the other hand, if your class method does not fulfill the required functionality, you can derive a new class from this base class and update the methods functionality in the derived class using overriding.

Lets see how this can be achieved and also understand their differences.

Method Overloading
a. Overloading means providing different function implementation with same name but with different signatures(return type and input arguments). Both the functions should be declared with the overload keyword.
b. Method overloading is done in the same class. Depending on the argument passed, .net picks up the respective function accordingly.

public class()
{
void myFunction(int i);
void myfunction(string s);
}

c. Overloading is resolved at compile time.

Method Overriding
a. Overriding means providing different function implementation in the derived class with same name and same signature. Overriding allows you to change the behaviour of the function in the child/derived class.
b. You can override a method in the derived class only if you declare the function as virtual in the base class. Method overriding is done in different classes - base class and derived class.

Base Class function
public virtual void myFunction();

Derived Class function
public override void myFunction();

c. Overriding is resolved at runtime.

Difference between a Struct and Class

Posted by Techie Cocktail | 6:40 PM | | 0 comments »

Below are some differences:

Class
a. Classes are reference types. When the object of the class gets created, it gets the memory allocation in the heap.
b. Classes support inheritance.
They can be inherited from a class or a struct.

c. Class supports instance field initialization.

class myClass
{
int a =10; //no error.
public void func( ) {..//do something...}
}

d. Class objects can be assigned null value as they are of reference types.
e. Classes are passed by reference as a parameter to a function.
f. Classes can have explicit parameterless constructors.

class myClass
{
int a = 10;
myClass()
{
}
}

g. All fields of the class need not be initialized in its constructor.
As seen in the below code, its alright to initialize any or all fields of a class.

class myClass
{
int a;
int b;

myClass()
{
a = 10;
}
}

Struct
a. Structs are value types. They get the memory allocation depending on where they are declared. If declared within the function, they are placed on stack and if they are member of a reference type then they get allocated in the heap.
b. Struct does not support inheritance, hence a struct members cannot be protected & protected internal access specifiers.
c. Struct does not support instance field initialization.

struct myStruct
{
int a = 10; //syntax error.
public void func( ) {...//do something...}
}


d. Struct variables cannot be assigned null as they are value types.
e. Structs are passed by Val as a parameter to function.
f. Structs cannot have explicit parameterless constructors.

struct myStruct
{
int a;
int b;

public MyStruct() //error
{
a = 10;
b = 20;
}
}

g. It is mandatory for the fields of the struct to be initialized in the struct constructor.

The below code gives error because 'b' is not initialized in the struct constructor and get the following error:
"Field 'namespace.class.myStruct.b' must be fully assigned before control is returned to the caller"

struct myStruct
{
int a;
int b;

public myStruct(int x)
{
a = 10;
}
}

Both Finalize() and Dispose() methods are called to clean up unmanaged resources. Dispose method is user-driven unlike Finalize which is called when the Garbage collection happens hence it is unpredictable. Hence dipose is generally preferred over Finalize if you want to clean up unmanaged resources in your program thereby increasing the performance.

Following are some more points:

Finalize()
a. Finalize() method cannot be called by the user, it is called automatically by the Garbage collector when an object goes out of scope or inaccessible.
b. The finalize method is protected and hence it can be accessed through the containing class or its derived class.
c. As the class designer, it is always safe to provide the Finalize method. This is in case if the programmer fails to call the Dispose method on the unmanaged resoures, it would cause permanent leak of memory which can hamper performance. So to not to take the blame on yourself, providing Finalize method is always a good practise.

Dispose()
a. Dipose() method is called by the user to free up the unmanaged resources such as files, streams, database connections and handles.
b. When implementing dispose, after calling dispose, call GC.SupressFinalize method in order to prevent Finalize method from running to prevent performance issues.
c. The IDiposable interface contains the dipose method with no arguments and returns void.

Polymorphism C# .Net

Posted by Techie Cocktail | 11:47 AM | | 1 comments »

Polymorphism is one of the powerful OOPs features in .Net. The word polymorphism means 'many forms', a type or a class can have different forms.
When a class is derived from a base class, it inherits the base class's members and methods.

There are two options here:
a. The derived class can replace the base class method completely with the new implementation. This is achieved by using 'new' keyword in the derived class method. The derived class method can be called using derived class's instance. Whereas the base class method can be called by casting the derived class instance to the base class.

Let’s see this by an example to understand clearly.


using System;
using System.Collections.Generic;
using System.Linq;

namespace Vehicle
{
class Program
{
class car
{
public car() { }

public virtual void body()
{
Console.WriteLine("Generic car model");
}
}

class sedan : car
{
public sedan() { }

public new void body()
{
Console.WriteLine("4 door car model");
}
}

class coupe : car
{
public coupe() { }

public new void body()
{
Console.Write("2 door car model");
}
}

static void Main(string[] args)
{
sedan _sedan = new sedan();
_sedan.body(); //prints "4 door car model"

//case derived class instance to base class to call the base class's method.
((car)_sedan).body(); //prints "Generic car model"
Console.Read();
}
}
}

b. The derived class can inherit the base class's method implementation completely. The derived class method can also add its own implementation in addition. This can be achieved by overriding the virtual base class method. That means that the base class method should be defined with the 'virtual' keyword and the derived class method should be defined using 'override' keyword.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Vehicle
{
class Program
{
class car
{
public car() { }

public virtual void body()
{
Console.WriteLine("Generic car model");
}
}

class sedan : car
{
public sedan() { }

public override void body()
{
base.body();
Console.WriteLine("4 door car model");
}
}

class coupe : car
{
public coupe() { }

public override void body()
{
Console.Write("2 door car model");
}
}

static void Main(string[] args)
{
sedan _sedan = new sedan();
_sedan.body(); //prints "Generic car model" followed by "4 door car model"
Console.Read();
}
}
}

Difference between a Const and Readonly

Posted by Techie Cocktail | 12:28 AM | | 1 comments »

Below are some differences:

Const
a. const member field must be initialized at the time of declaration.
b. const field can have only one value which is defined at the time of declaration.
c. const can't be static.

Readonly
a. readonly field can be initialized at the time of declaration or in the class's consructor.
b. The value of the readonly field once set at the time of declaration, can be updated at runtime.
c. readonly can be either instance-level or static.

Look at a const field to be a compile-time constant and readonly field as a runtime constant.

Difference between a thread and process

Posted by Techie Cocktail | 12:25 AM | | 0 comments »

Below are some differences:

Process
a. A process is like an individual executing program having its own memory space & system resources.
b. Process has its own seperate memory space.
c. A process can contain a number of threads.

Thread
a. Thread are like an OS environment features which run in the context of a process. Threads are way to split different tasks of a program to improve performance.
b. Threads share resources of the process in which they resides.
c. Threads are contained within the process. Reverse is never possible.

Debugging and its techniques in .Net

Posted by Techie Cocktail | 6:42 PM | | 0 comments »

Debugging is one of the most important aspects of developing quality code. It helps a developer to analyze the code at various points. Use of effective debugging techniques helps better understanding and fast analysis of the code thereby increasing the productivity.

Debugging often involves verification of the code, analysis of the code functionality when a bug is reported, or understanding of a pre-written code.

It is really very useful to understand the strong debugging techniques that .net language and IDE provides. Let us see some good debugging techniques available.

1. F9, F5, F10, F11 – Most of us are already familiar with these Hot Keys.
F9 – Used to set up breakpoint.
F5 – Starts the debugging.
F10 – Step Over.
F11 – Step into.
Shift + F11 – Step Out.

These options are available in the Debug menu of IDE.

2. Debug Windows: Following windows will be useful to look at for analyzing various output results. I am not going into details to explain these windows as this is out of scope of this article.

Output, locals, watch, call stack, Immediate.

3. Debugger and Debug Class available in system.diagnostics namespace. These are coding approaches of debugging in .net.

Debugger:
Has some important methods useful for debugging like Break() and Log().

Break() is similar to the breakpoint that we put using F9 Hot Key. But using this approach, we can make it conditional.


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int result = division(1, 2);
if (result == 0)
{
Debugger.Break();
}
}

static private int division(int num1, int num2)
{
return num1 / num2;
}
}
}

In the above example, if the result is non-zero, the debugger will not get activated.

Log() method is used to log the data to the attached debugger. The below example prints the output to the output window.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int num1 = 1;
int num2 = 2;
int result = division(num1, num2);
if (result == 0)
{
Debug.Listeners.Clear();
DefaultTraceListener _dtl = new DefaultTraceListener();
Debug.Listeners.Add(_dtl);
Debugger.Log(2, "Zero Result", string.Format("The result of {0}/{1} is zero", num1, num2));
}
}

static private int division(int num1, int num2)
{
return num1 / num2;
}
}
}

There are many other Listener classes available in .net. Best bet would be MSDN for reference.

Debug:
The Debug class has several important and useful methods to help efficient debugging. Let’s look at them.

Assert() – Pops up a message box if the assert condition fails.

static void Main(string[] args)
{
int num1 = 1;
int num2 = 2;

Debug.Assert(num1 > num2, "Num1 is less than Num2");

int result = division(num1, num2);
}

the user gets the message box as below with the message shown at the top followed by the stack trace.


Fail() – The fail method is similar to the Assert() method. Except that it does not evaluates the condition. It simply breaks at the Debug.Fail() line with the message & stack trace in the message box.

Write(), WriteIf() – Writes the output to the output window or any attached trace listener.

The only difference between Write() & WriteIf() is that WriteIf() is executed only if the specific condition is met.

Debug.Listeners.Clear();
DefaultTraceListener _dtl = new DefaultTraceListener();
_dtl.LogFileName = @"d:\logging.txt";
Debug.Listeners.Add(_dtl);
Debug.AutoFlush = true;
Debug.Write("Message from debug.write method");
Debug.WriteIf(num1 > num2, "Check the numbers");

Note, the issue with these methods is that they write the next output in the same line. To solve this problem we have Debug.WriteLine() & Debug.WriteLineIf() methods.

WriteLine(), WriteLineIf() - They do the same thing as Write() and WriteLineIf() except that they write the output to the attached listener in the new line.

Debug.Listeners.Clear();
DefaultTraceListener _dtl = new DefaultTraceListener();
_dtl.LogFileName = @"d:\logging.txt";
Debug.Listeners.Add(_dtl);
Debug.AutoFlush = true;
Debug.WriteLine("Message from debug.write method");
Debug.WriteLineIf(num1 > num2, "Check the numbers");

These are some of the useful methods you can perform good debugging. There are more useful methods available. I suggest MSDN as the best reference to research.

Also note, the above Debugger or Debug methods will work only if you run your program in the Debug mode. In release mode they act like disabled pieces. That’s the advantage of using these for debugging.

4. Debugging Attributes
Other than these powerful debugging methods, there are various debugging attributes available to ease the debugging output readability.

The attributes that are commonly used are DebuggerDiplay & DebuggerBrowsable.

I won’t get too much into details for this for the sake of brevity. Refer this like for its details MSDN

5. Trace Class
Trace is also a part of System.Diagnostics namespace. Trace class works in line with the Debug Class. Their methods are pretty much similar to that of debug class. They use TraceListeners instead of DebugListeners to print the trace output.

The only differences between Trace and Debug classes are:
Trace statements work both in Release and Debug mode whereas Debug statements works only in Debug mode.

Both trace and debug classes are used to understand the behavior of the application program. The main purpose of the trace is to understand the program flow execution whereas debug class purpose is to find out why a particular error occurs.

Happy Debugging!