Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, September 7, 2009

Classes (C# Programming Guide)

A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope. At that time, the CLR marks it as eligible for garbage collection.

Declaring Classes

Classes are declared by using the class keyword, as shown in the following example:

public class Customer
{
//Fields, properties, methods and events go here...
}


The class keyword is preceded by the access level. Because public is used in this case, anyone can create objects from this class. The name of the class follows the class keyword. The remainder of the definition is the class body, where the behavior and data are defined. Fields, properties, methods, and events on a class are collectively referred to as class members.

Creating Objects

Although they are sometimes used interchangeably, a class and an object are different things. A class defines a type of object, but it is not an object itself. An object is a concrete entity based on a class, and is sometimes referred to as an instance of a class.

Objects can be created by using the new keyword followed by the name of the class that the object will be based on, like this:

Customer object1 = new Customer();


When an instance of a class is created, a reference to the object is passed back to the programmer. In the previous example, object1 is a reference to an object that is based on Customer. This reference refers to the new object but does not contain the object data itself. In fact, you can create an object reference without creating an object at all:

Customer object2;


MS do not recommend creating object references such as this one that does not refer to an object because trying to access an object through such a reference will fail at run time. However, such a reference can be made to refer to an object, either by creating a new object, or by assigning it to an existing object, such as this:

Customer object3 = new Customer();
Customer object4 = object3;


This code creates two object references that both refer to the same object. Therefore, any changes to the object made through object3 will be reflected in subsequent uses of object4. Because objects that are based on classes are referred to by reference, classes are known as reference types.

Source : http://msdn.microsoft.com/en-us/library/x9afc042.aspx

Properties (C# Programming Guide)

Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

In this example, the TimePeriod class stores a time period. Internally the class stores the time in seconds, but a property named Hours enables a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.

Example
class TimePeriod
{
private double seconds;

public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}

class Program
{
static void Main()
{
TimePeriod t = new TimePeriod();

// Assigning the Hours property causes the 'set' accessor to be called.
t.Hours = 24;

// Evaluating the Hours property causes the 'get' accessor to be called.
System.Console.WriteLine("Time in hours: " + t.Hours);
}
}
// Output: Time in hours: 24



Properties Overview

# Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.

# A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. For more information, see Asymmetric Accessor Accessibility (C# Programming Guide).

# The value keyword is used to define the value being assigned by the set accessor.

# Properties that do not implement a set accessor are read only.

Source : http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx

Saturday, September 5, 2009

Using enum in C# for smart coding








Most of us have written these (Sample 1 & Sample 2) kind of code snippet in our student or even professional life:


Sample 1 (C# Code):
string employeeType = employeeTypeComboBox.Text;
if (employeeType == "Permanent")
{
CalculateSalary();
}
else if (employeeType == "Worker")
{
CalculateWages();
}
else
{
// Do nothing
}




Sample 2 (C# Code):
string studentType = studentTypeComboBox.Text;
if (studentType == "Regular")
{
// Do Something
}
else if (studentType == "Private")
{
// Do Something
}
else
{
// Do nothing
}
In these two samples, user input is taken in a string valriable (employeeType /studentType) from a ComboBox and compare the variable with some discrete hard-coded string values (Permanent/Worker/Regular/Private).
What will happen if you type (some of you has faced these sad experiences) Parmanent instead of Permanent in Sample 1? Definitely, CalculateSalary() method will be not called and even program doesn’t show you any error message (any compile error). In best case, You will find out this problem during development and fix it immediately. But in worst case this problem arises after demployment.





Is there any solution where my typo will be detected earliar and show me a compile error?
Yes. Try emun.




See Sample Code 3, the more smart version of Sample code 1. Here you have no typo option.




Sample Code 3
enum EmployeeType
{
Permanent,
Worker
}
string employeeType = employeeTypeComboBox.Text;
if (employeeType == EmployeeType.Permanent.ToString())
{
CalculateSalary();
}
else if (employeeType == EmployeeType.Worker.ToString())
{
CalculateWages();
}
else
{
//Do Nothing
}




Believe me still you have chance to improve the code quality of Sample Code 3. Just see the Sample Code 4, I have wipe out all kinds of string variable from Sample Code 3.




Sample Code 4:
EmployeeType selectedEmployeeType = (EmployeeType)Enum.Parse(typeof(EmployeeType), employeeTypeComboBox.Text);
if (selectedEmployeeType == EmployeeType.Permanent)
{
CalculateSalary();
}
else if (selectedEmployeeType == EmployeeType.Worker)
{
CalculateWages();
}
else
{
//Do Nothing
}




Even, as your input comes from employeeTypeComboBox, don’t write hard-coded string in it’s item list, rather do it:
employeeTypeComboBox.DataSource = Enum.GetNames(typeof(EmployeeType));



So, why enum?

a) To improve code clarity


b) Make the code easier to maintain

c) Getting error at earlier stage


Note:

a) You can define enum inside or outside of class, but not inside of method or property.

b) The list of names contained by a particutar type of enum called enumerator list.





More About enum:

a) If you want you can keep value with each name in enumerator list. Example:




enum Priority
{
   Critical = 1,
   Important = 2,


  Medium = 3,

   Low = 4

};





You will get this value by type casting to the related type.

int priorityValue = (int) Priority.Medium;






b) Another nice thing, you can easily iterate through enumerator list.

foreach(Priority priority in Enum.GetValues(typeof(Priority)))
{
   MessageBox.Show(priority.ToString());


}

or even
for (Priority prio = Priority.Low; prio >= Priority.Critical; prio--)
{
   MessageBox.Show(prio.ToString());


}




Conclusion:

You should avoid string operation (specially comparison) because it decreases readability and introduces opacity. But using enum you can increase code readability, discover bugs in design time and keep your code more easy to maintain. So, Instead of string operation we should use enum (where applicable)  as described in this discussion.



Source : Using enum in C# for smart coding (http://ztiemoon.blogspot.com/)

Sufferings with switch smell


Introduction
In my first blog, Using enum in C# for smart coding, described code snippets suffer with switch smell. So, here, I am explaining what the switch smell is, what’s wrong with it and how to avoid it?
 
Most of the time, our source code suffers with several bad smells. Authors of a great book, Refactoring: Improving the Design of Existing Code, explain these smells with refactoring techniques. Here, I try to explain how switch smell introduces unnecessary complexity, reduces flexibility and leaves a class with vague responsibilities (from caller’s point of view).



Code Explanation
In the following two samples (Sample 1 & Sample 2), I have written a class, Calculator which can perform four basic arithmetic operation addition, subtraction, division and multiplication on two numbers.
Note: Here all code snippets are written in C#.


Sample 1:
public enum Operation
{
    Add,
    Subtract,
    Multiply,
    Divide
}
public class Calculator
{
    public double Calculate(double firstNo, double secondNo, Operation operation)
    {
        switch (operation)
        {
            case  Operation.Add:
            {
                return (firstNo + secondNo);
                break;
            }
            case Operation.Subtract:
            {
                return (firstNo - secondNo);
                break;
            }
            case Operation.Multiply:
            {
                return (firstNo * secondNo);
                break;
            }
            case Operation.Divide:
            {
                return (firstNo / secondNo);
                break;
            }
            default:
            {
                throw new ArgumentException("Incorrect Argument");
            }
        }
    }




Sample 2:
public class Calculator
{
    public double Add(double firstNo, double secondNo)
    {
        return (firstNo + secondNo);
    }
    public double Subtract(double firstNo, double secondNo)
    {
        return (firstNo - secondNo);
    }
    public double Multiply(double firstNo, double secondNo)
    {
        return (firstNo * secondNo);
    }
    public double Divide(double firstNo, double secondNo)
    {
        return (firstNo / secondNo);
    }
}




Calculator of Sample 1 provides these functionalities with its Calculate() method whereas Calculator of Sample 2 has four methods for four specific functionalities.
In Sample 1, I introduce switch statement inside Calculate() method to distinguish the request of client code whether it (client request) wants to add, subtract, multiply or divide. On the other hand, in Sample 2, as each functionality is implemented in separate method I haven’t bothered with condition-checking (switch statement).



Comparison
Now, the question is: Which class is better than other one?
From design point of view Calculator is responsible for four distinct arithmetic operations, so it should have four methods in implementation level.
In Sample 1, Calculator has only a single method, Calculate() which perform four arithmetic operations. As a result it represents poorly self-documentation and introduces unnecessary complexity. It suffers with switch smell. As a result Calculator responsibilities is not concrete here. So, caller of the Calculate() method has to decide what it (caller) wants from Calculate() method by setting the parameter.
On the other hand, in Sample 2, interface of Calculator is clearer and also it is self-documented.
Sample 2 is more flexible than Sample 1. Suppose if I want to provide another functionality to add three numbers.
For Sample 2, I quickly write overload Add() method as follows with reusability.





public double Add(double firstNo, double secondNo, double thirdNo)
{
    return Add(Add(firstNo, secondNo), thirdNo);
}




But what’s for Sample 1?  :-((. I have to follow some ugly and stupid ways to implement this functionality which introduces more complexity, code repetition, procedural thoughts etc.


More..
In Refactoring: Improving the Design of Existing Code, Authors explain this problem (Sample 1)  under bad small of switch statement and also show several ways (‘Replace type code with Subclasses’, ‘Replace type code with State/Strategy’, ‘Replace Parameter with Explicit Method’ how to refactor this smell. At the same time, authors describe ‘Parameterize Method’ which seems reverse of our discussion.


Conclusion
Each method of a class should represents a single activity, must be concrete and self-documented. One more activities in a single method (by switch smell) or one activity in several methods (I will discuss it another day) introduces complexicity and ambiguous interface, hinders changes, intencifies duplication and leave the class poorly self-documented.




Source : Sufferings with switch smell (http://ztiemoon.blogspot.com/)

Sunday, August 23, 2009

C# Keywords Definition

abstract
A class modifier that specifies that the class must be derived-from to be instantiated.

as
A binary operator type that casts the left operand to the type specified by the right operand and that returns null rather than throwing an exception if the cast fails.

base
A variable with the same meaning as this, except that it accesses a base-class implementation of a member.

bool
A logical datatype that can be true or false.

break
A jump statement that exits a loop or switch statement block.

byte
A one-byte, unsigned integral data type.

case
A selection statement that defines a particular choice in a switch statement.

catch
The part of a try statement that catches exceptions of a specific type defined in the catch clause.

char
A two-byte, Unicode character data type.

checked
A statement or operator that enforces arithmetic bounds checking on an expression or statement block.

class
An extendable reference type that combines data and functionality into one unit.

const
A modifier for a local variable or field declaration that indicates that the value is a constant. A const is evaluated at compile time and can be only a predefined type.

continue
A jump statement that skips the remaining statements in a statement block and continues to the next iteration in a loop.

decimal
A 16-byte precise decimal datatype.

default
A marker in a switch statement specifying the action to take when no case statements match the switchexpression.

delegate
A type for defining a method signature so delegate instances can hold and invoke a method or list of methods that match its signature.

do
A loop statement to iterate a statement block until an expression at the end of the loop evaluates to false.

double
An eight-byte, floating-point data type.

else
A conditional statement that defines the action to take when a preceding if expression evaluates to false.

enum
A value type that defines a group of named numeric constants.

event
A member modifier for a delegate field or property that indicates that only the += and -= methods of the delegate can be accessed.

explicit
An operator that defines an explicit conversion.

extern
A method modifier that indicates that the method is implemented with unmanaged code.

false
A Boolean literal.

finally
The part of a try statement to execute whenever control leaves the scope of the try block.

fixed
A statement to pin down a reference type so the garbage collector won't move it during pointer arithmetic operations.

float
A four-byte floating-point data type.

for
A loop statement that combines an initialization statement, continuation condition, and iterative statement into one statement.

foreach
A loop statement that iterates over collections that implement IEnumerable.

get
The name of the accessor that returns the value of a property.

goto
A jump statement that jumps to a label within the same method and same scope as the jump point.

if
A conditional statement that executes its statement block if its expression evaluates to true.

implicit
An operator that defines an implicit conversion.

in
The operator between a type and an IEnumerable in a foreach statement.

int
A four-byte, signed integral data type.

interface
A contract that specifies the members that aclass or structmay implement to receive generic services for that type.

internal
An access modifier that indicates that a type or type member is accessible only to other types in the same assembly.

is
A relational operator that evaluates to true if the left operand's type matches, is derived-from, or implements the type specified by the right operand.

lock
A statement that acquires a lock on a reference-type object to help multiple threads cooperate.

long
An eight-byte, signed integral data type.

namespace
A keyword that maps a set of types to a common name.

new
An operator that calls a constructor on a type, allocating a new object on the heap if the type is a reference type, or initializing the object if the type is a value type. The keyword is overloaded to hide an inherited member.

null
A reference-type literal that indicates that no object is referenced.

object
The type all other types derive from.

operator
A method modifier that overloads operators.

out
A parameter modifier that specifies that the parameter is passed by reference and must be assigned by the method being called.

override
A method modifier that indicates that a method of a class overrides a virtualmethod of a class orinterface.

params
A parameter modifier that specifies that the last parameter of a method may accept multiple parameters of the same type.

private
An access modifier that indicates that only the containing type can access the member.

protected
An access modifier that indicates that only the containing type or derived types can access the member.

public
An access modifier that indicates that a type or type member is accessible to all other types.

readonly
A field modifier specifying that a field can be assigned only once, either in its declaration or in its containing type's constructor.

ref
A parameter modifier that specifies that the parameter is passed by reference and is assigned before being passed to the method.

return
A jump statement that exits a method, specifying a return value when the method is non-void.

sbyte
A one-byte, signed integral data type.

sealed
A class modifier that indicates a class cannot be derived-from.

set
The name of the accessor that sets the value of a property.

short
A two-byte, signed integral data type.

sizeof
An operator that returns the size in bytes of a struct.

stackalloc
An operator that returns a pointer to a specified number of value types allocated on the stack.

static
A type member modifier that indicates that the member applies to the type rather than to an instance of the type.

string
A predefined reference type that represents an immutable sequence of Unicode characters.

struct
A value type that combines data and functionality in one unit.

switch
A selection statement that allows a selection of choices to be made based on the value of a predefined type.

this
A variable that references the current instance of a class or struct.

throw
A jump statement that throws an exception when an abnormal condition has occurred.

true
A Boolean literal.

try
A statement that provides a way to handle an exception or a premature exit in a statement block.

typeof
An operator that returns the type of an object as a System.Type object.

uint
A four-byte, unsigned integral data type.

ulong
An eight-byte, unsigned integral data type.

unchecked
A statement or operator that prevents arithmetic bounds checking on an expression.

unsafe
A method modifier or statement that permits pointer arithmetic to be performed within a particular block.

ushort
A two-byte, unsigned integral data type.

using
A directive that specifies that types in a particular namespace can be referred to without requiring their fully qualified type names. The keyword is overloaded as a statement that allows an object that implements IDisposable to be disposed of at the end of the statement's scope.

value
The name of the implicit variable set by the set accessor of a property.

virtual
A class method modifier that indicates that a method can be overridden by a derived class.

void
A keyword used in place of a type for methods that don't have a return value.

volatile
A field modifier indicating that a field's value may be modified in a multithreaded scenario and that neither the compiler nor runtime should perform optimizations with that field.

while
A loop statement to iterate a statement block while an expression at the start of each iteration evaluates to false.

Source :
C# Essentials, 2nd Edition (By Ben Albahari, Peter Drayton, Brad Merrill)
Publisher : O'Reilly