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

Saturday, November 26, 2011

Arrays 2

When you declare an array, you don’t have to specify the capacity of the array.

You have to do this while initializing arrays.

[VB] Dim v as Integer()

[CS] int[] v;

This is just declaration of integer array variable. Value of v is nothing/null.

Initializing arrays with 5 elements

[VB] v =  new Integer(4){}

[CS] v =  new int[5]

in Visual Basic, the value specified within the parenthesis are Upper bound and the lower bound is always zero. Hence it can hold 5 elements (0,1,2,3,4).

VB developers: To avoid confusion, you can declare like this

[VB] v = new Integer(0 to 4){}

Array elements can be accessed with indexes

[VB] Dim n as Integer = v(2)

[CS] int n = v[2]

Index can also be variable

[VB]

    Dim index as integer = 2

    Dim n as Integer = v[index]

[CS]

    int index = 2;

    int n = v[index];

Accessing array elements by indexes gives a great opportunity for working with large set of data.

You can access series of elements using looping constructs.

[VB]

    For index as Integer = 0 to 4

        v(index) = index * 10

        Console.WriteLine(v(index))

    Next

[CS]

    for(int index=0;index<5;index++)

    {

        v[index] = index * 10;

        Console.WriteLine(v[index]);

    }

Also you can access elements with foreach loops

[VB]

    Foreach element as Integer in v

        Console.WriteLine(element)

    Next

[CS]

    foreach(int element in v)

    {

        Console.WriteLine(v[element])

    }

Arrays

You can use arrays when you have a fixed size collection of data with similar types.

Declaration

[VB] Dim v as Integer()

[CS] int[]

Initialization with specific size

[VB] Dim v as Integer() = new Integer(9){}

[CS] int[] v = new int[10]

Initialization with Data

[VB] Dim v as Integer() = {1,2,3,4}

[CS] int[] v = {1,2,3,4}

You can use object arrays, if you do not want to restrict your data to specific type.

Monday, November 21, 2011

Byte Array/Binary

To store byte array or binary data, Base64 string format is commonly used.

Convert.ToBase64String

This can help you to store binary data to Xml files and string columns in database.

Common Data Types

String and Byte array are the common data types to keep any data types. Of course, sometimes we may need to write code to do that.

String to Number conversion

To convert a string to a number, you can use one of the following methods

<DataType>.Parse
Convert.To<DataType>

For example, to convert a string to int, you can use

int.Parse
or
Convert.ToInt32

Console Screen: runs and disappears?

When you compile and execute a console application, it may run fast as disappear. To get rid of this, you can add

Console.ReadKey

Statement in the end, to pause it. It will wait until you press a key.

Static Members

If you have a set of variable members those don’t change for each instance of that class, you can declare them as Static Variable Members.

If a method inside class, accesses no member variables you can declare the method as Static Methods.

Member methods can not use This (VB)/ base (CS) object, as there is no specific instance associated with it.

For accessing static members, you don’t have to instantiate the class. You can directly call the member with class name.

Saturday, November 19, 2011

Variable Declaration

If you are a VB6 or ASP developer, and if you do not want to declare variables, you can do that by putting this line in the First line of the Source Code file

Option Explicit Off

Link: http://msdn.microsoft.com/en-us/library/y9341s4f%28v=vs.80%29.aspx

But it is better to turn this On, so that you can avoid misspelled variable names

Example

intToatl = intTotal + intValue

Friday, November 18, 2011

Solution, Project , Assembly and Namespace Names

In Visual Studio, sometimes we get confusion about Solution, Project , Assembly and Namespace Names.

Solution is a container for holding one or more related projects. Name it in a way to identify the entire concept for which we are going to create the Visual Studio Projects.

Project is a container for holding one or more related source files which are grouped together to give a single Assembly or Output (an exe or dll file). Name it in a way to identify the concept implemented in the project.

Assembly Name is the name given to the actual output (exe or dll file).

Namespace is a container for holding one or more types, which resides in an assembly. An assembly or Project can have more than one namespaces.

By default all these are same, but you can have all them with different names.

Console Applications

Console applications are the best way to perform many tasks which needs automation by means of batch files and scheduled tasks.

Command line arguments provides you a way to send inputs to the console applications.

In Command prompts redirection operators helps you to link sequence of command line operations.

 

Links

Command line arguments: http://msdn.microsoft.com/en-us/library/aa288457(v=vs.71).aspx

Redirection operators: http://technet.microsoft.com/en-us/library/bb490982.aspx

Wednesday, November 16, 2011

Welcome

Welcome to the tips blog for Microsoft .Net 4.0 Framework. Here you can find, exclusive tips and articles regarding .Net Framework 4.0 with C# and VB.Net.