Thursday, December 22, 2011

Snippet: Validating whether a string is integer or not

bool bInt;
int intValue;
bInt = int.TryParse(strData, out intValue);
if (bInt == true)
{
  // Successfully parsed
}
else
{
  // String is in numeric format
}

Best Practices: Exception handling Myth #1

MYTH#1 DO NOT SIMPLY RETHROW A CAUGHT EXCEPTION

Rethrowing the same Exception is an “Exception Handling” method.

In the catch block, there must be some work to handle the Exception.

[VB]

Try

  ‘ Do some code

Catch ex as Exception

  Throw ex

End Try

[CS]

try

{

  // Do some code

}

catch(Exception ex)

{

  throw ex;

}

This will suppress the actual line where the error was thrown and it will show the rethrown line as the actual source of exception.

 

For rethrowing the exception, you can simply create a new Exception with the caught exception as Inner Exception.

[VB]

Try

  ‘ Do some code

Catch ex as Exception

  Throw New Exception(“Process Failed”, ex)

End Try

[CS]

try

{

  // Do some code

}

catch(Exception ex)

{

  throw new Exception(“Process Failed”, ex);

}

Best Practices: Initialization Myth #1

[Note] I have used DataTable only for explaining. It can be any data type.

Usually we do the mistake of initializing unnecessarily like this.

[VB]

Dim dt as New DataTable

dt= CreateDataTable()

[CS]

DataTable dt= new DataTable();

dt=CreateTable();

We don’t have to initialize the dt variable here and it is unnecessary. Because we are overwriting it.

We can just declare the variable and then assign the value from the function or any other expressions.

[VB]

Dim dt as DataTable

dt= CreateDataTable()

[CS]

DataTable dt;

dt=CreateTable();

Or Simply

[VB]

Dim dt as DataTable = CreateDataTable()

[CS]

DataTable dt = CreateTable();

Sunday, December 18, 2011

Designing a class 6: Restricting a class from inheriting

A class can be marked as complete so that it can not be inherited further. You can use the following keyword to achieve this.

[VB] NotInheritable

[CS] sealed

Code Sample

[VB] Public NotInheritable Class Manager

[CS] public sealed class Manager

Sunday, December 11, 2011

Designing a class 5: Restricting the instantiation

An object can be restricted from instantiation to mention that it is not complete.

This can be accomplished by declaring the class as abstract.

Keyword:

[VB] MustInherit

[CS] abstract

 

Code Sample:

[VB] Public MustInherit class EmployeeBase

[CS] public abstract class EmployeeBase

Designing a class 4: Member access modifiers

Members within a class can be restricted from which those members can be accessed. Those restrictions can be applied by prefixing the access modifiers while declaring them.

 

Access Modifiers

Private: private members are accessible only from the code blocks within the class.

Keyword

[VB] Private

[CS] private

Protected: protected members are accessible from the code blocks of the class and the code blocks of its derived class.

Keyword

[VB] Protected

[CS] protected

Friend/Internal: friend/internal members are accessible from the code blocks anywhere within the assembly where the class resides.

Keyword

[VB] Friend

[CS] internal

Protected friend/Protected internal: these members can be accessed from the code blocks anywhere within the assembly where the class resides and the code blocks from the derived classes declared in other assemblies.

Keyword

[VB] Protected friend

[CS] protected internal

Public: public members does not have any restrictions

Keyword

[VB] Public

[CS] public

Designing a class 3: Shared or Static members

Often, some data or operations are not related to a specific instance. Instead they are related to the class itself. These data and operations are common to all instances. These members are called as Static members or Shared members.

Keyword used to define a member as static or shared.

[VB] Shared

[CS] static

 

Designing a class 2: Instances

Classes are considered a blueprints of concepts. To realize the blueprints, we have to create an instance of a class. Like a blueprint, a blueprint can be used for several realizations.

Realization can be done by using “new” keyword.

Employee alice = new Employee();

Employee bob= new Employee();

Here the blueprint Employee has been realized as alice and bob. Or we can say, class Employee has been instantiated as alice and bob.

When creating instances of class, they are linked with their own memory allocation of Fields (Member variables) so that data of each instance are isolated from other instances.

Designing a class: 1

Classes are designed mostly based on a concept and its related data and operations.

Considering the implementation of an Office, we can think of the following objects.

  • Office
  • Department
  • Employee

While implementing an office class we can think of the following data and operations

  • Data
    • Name
    • Location
    • Contact Details etc
  • Operations
    • PrepareSalary

Local variables and Member Variables/Fields

Variables declared within a code block of a class member are called as local variables.

Variables declared within a class and not within a code block of its member are called Member Variables or Fields.

Abstract Classes and Concrete Classes

Abstract classes are the classes those are not complete. They should be derived so that becomes usable. Some members of the abstract class does not know its implementation and the derived class can implement them to complete the purpose of the base class.

In contrast, Concrete classes have full implementation of their purpose.

abstract class EmployeeBase
{
    public int ID { get; set; }
    public string Name { get; set; }
    public double BasicPay { get; set; }
    public abstract double CalcSalary();
}

class Clerk: EmployeeBase
{
    public override double CalcSalary()
    {
        double HRA= BasicPay * .40;
        double DA= BasicPay * .25;
        double PF= BasicPay * .12;
        return BasicPay + HRA + DA - PF;
    }
}

Saturday, December 10, 2011

StringBuilder

If you are appending to a string menu many times, it is better to use StringBuilder instead as it improves performance.

Wednesday, December 07, 2011

Inheritance and Type Casting

When a derived class is inherited from a base Class, objects of derived class can be assigned to variable of base class.

[CS]

Employee emp= new Employee();

Person per= emp;

 

[VB]

Dim emp as new Employee()

Dim per as Person = emp

When derived class object is assigned to base class variable, we can only access base class members through that variable. But we can access derived class members through derived class variables or type casting the base class back to derived class.

[CS]

per.Name = “Muthukrishnan”;

emp.Department = “Technical”;

(per as Employee).DOJ = datJoiningDate;

 

[VB]

per.Name = “Muthukrishnan”

emp.Department = “Technical”

CType(per,Employee).DOJ = datJoiningDate

Here type casting is only possible because the “per” base class variable holds derived class object.

Base class objects can not be type casted to derived class variables.

For example

[CS]

Person per = new Person();

Employee emp = per;

 

[VB]

Dim per as new Person()

Dim emp as Employee = per

Above code will through error during compile time.

We can force the type casting so that the code can be compiled.

[CS]

Person per = new Person();

Employee emp = (per as Employee);

 

[VB]

Dim per as new Person()

Dim emp as Employee = CType(per, Employee)

But above code will throw error during runtime.

Arrays 3

Class System.Array is the base class for all arrays.

Length property gets the total number of elements in the Array

GetValue property gets element value in the given index

SetValue property sets a given element value in the index specified in the second parameter of that method

class Program
{
    static void Main(string[] args)
    {
        int[] a = new int[5];
        System.Array o = a;
        Console.WriteLine("Array Length:" + a.Length.ToString());
        // Assign element values
        for (int i = 0; i < o.Length; i++)
        {
            int intValue = i * i;
            o.SetValue(intValue, i);
        }
        // Retrieve element values
        for (int i = 0; i < o.Length; i++)
        {
            Console.WriteLine("Element " + (i + 1).ToString() + ":" + o.GetValue(i));
        }
        Console.ReadKey();
    }
}

Saturday, December 03, 2011

Command Line Arguments: Sample 1

Sample for Console Application with Command line arguments

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Args count:" + args.Length.ToString());
        foreach (string arg in args)
            Console.WriteLine("\t" + arg);
    }
}

Sample outputs

MyApps>CmdLineApp.exe
Args count:0

MyApps>CmdLineApp.exe Hello World
Args count:2
        Hello
        World

MyApps>CmdLineApp.exe "Hello World" Command line application
Args count:4
        Hello World
        Command
        line
        application

MyApps>CmdLineApp.exe "Hello World" "Command line application"
Args count:2
        Hello World
        Command line application

Command Line Arguments 1

Command line arguments are the variable data those can be passed into applications as arguments when they are invoked.

When an application can have external inputs, we can pass those inputs to the applications when calling them.

Applications can be called through many methods.

  • Opening applications from windows explorer or desktop
    • For opening an application from windows explorer, we can just double click the executable file or we can press enter key after selecting it.
    • Inputs can not be passed to the application
  • Opening applications through shortcuts from windows explorer or desktop
    • We can create shortcut to application by selecting Create shortcut in the context menu of that application
    • Inputs can be changed by changing shortcuts property
  • Executing from Windows Console
    • We can execute the applications by going to specific directory and entering the application name. (More options are there which i haven’t explained here)
    • Inputs can be passed by typing them after the application name
  • Opening an associated file from windows
    • We can associate files to applications through few settings in windows registry. (Not explained here).
    • Associated file names can be passed as inputs to the application based on the registry setting
  • Programmatically invoking applications
    • We can write programs to invoke applications using methods specific to the programming language. (Process.Start in .Net)
    • Inputs can be specified explicitly in the programs.
  • Dragging a files or folders and dropping it on the application or on the application shortcuts
    • Dragged files or folder names are passed as inputs to the applications

Friday, December 02, 2011

Parameters: Call “by value” and “by reference” Arrays

Arrays are reference type objects. So you can change the elements of an array from methods that receives the array as byval argument

Parameters: Call “by value” and “by reference” 3

If we want to replace an object variable itself (not its property or field), we should mark the argument with “ref”

public void CreateTextBox(ref TextBox txt)
{
    if (txt == null)
            txt = new TextBox();
}

 

public void TestCreateControl()

{

    TextBox txtEmpID;

    CreateTextBox(ref txtEmpID);

    CreateTextBox(ref txtEmpID);

}

In this case, we should mark the argument txt with ref, otherwise the TextBox creation will not be reflected in the passed parameter.

In the first call, the txt object will be created and it will reflect in the txtEmpID. In the second call, as the txt is not null, it won’t create the TextBox object.

Parameters: Call “by value” and “by reference” 2

Reference type objects are already having reference in it. So mostly there will be no need to pass them by reference.

public void ChangeText(TextBox txt)
{
    txt.Text = DateTime.Now.ToString();
}

Whatever TextBox we pass it to this method, Text of that TextBox will be changed. There is no need to mark it with “ref” keyword.

Parameters: Call “by value” and “by reference”

When a parameter is send to a method as by value, the argument receiving the parameter will have copy of its value. When we change the argument variable within the method, it will not be reflected in the original parameter.

When a parameter is send to a method as by reference, the argument receiving the parameter will have the reference to the parameter. In effect, When we change the argument variable within the method, it will be reflected in the original parameter.

class Program
{
    static void Main(string[] args)
    {
        int v = 10;

        Console.WriteLine("Call by Value:");
        Console.WriteLine("Before Call:");
        Console.WriteLine("  v: " + v.ToString());

        SetDataByValue(v);

        Console.WriteLine("After Call:");
        Console.WriteLine("  v: " + v.ToString());

 

        Console.WriteLine();
        v = 10;
        Console.WriteLine("Call by Reference:");
        Console.WriteLine("Before Call:");
        Console.WriteLine("  v: " + v.ToString());

        SetDataByRef(ref v);

        Console.WriteLine("After Call:");
        Console.WriteLine("  v: " + v.ToString());
       
        Console.ReadKey();
    }

    static void SetDataByValue(int a)
    {
        a = a + 1;
    }

    static void SetDataByRef(ref int a)
    {
        a = a + 1;
    }
}

Output

Call by Value:
Before Call:
  v: 10
After Call:
  v: 10

 

Call by Reference:
Before Call:
  v: 10
After Call:
  v: 11