best practices for Good programming

best practices for Good programming


2.1.1Avoid having too large files.

If a file has more than 300~400 lines of code, you must consider refactoring code into helper classes.


2.1.2Avoid writing very long methods.

A method should typically have 1~25 lines of code. If a method has more than 25 lines of code, you must consider re factoring into separate methods.


2.1.3White Space

Blank lines improve readability by setting off sections of code that are logically related.

Two blank lines should always be used between sections of a source file. That is, two blank lines should follow:

  • the opening comment

  • the package statement

  • the import statements

  • the class and interface declaration

One blank line should always be used in the following circumstances:

  • Between methods

  • Between the local variables in a method and its first statement

  • Before a block or single-line comment.

  • Between logical sections inside a method to improve readability.

  • Use common sense and don't be afraid to put blank lines!



2.1.4Blank Spaces

Blank spaces should be used in the following circumstances:

  • A blank space should appear after commas in argument lists.

  • All binary operators except. Should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment ("++"), and decrement ("--") from their operands.

  • The expressions in a "for" statement should be separated by blank spaces.

example:


public void aMethod(int a, int b, int c, int d)

{

a += c + d;

a = (a + b) / (c * d);


printSize("size is " + foo);


for(expr1; expr2; expr3)

{

/* No Body */

}

}

















2.1.5Parentheses


It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems

if(a == b && c == d) // AVOID!

if((a == b) && (c == d)) // RIGHT









2.1.6Naming Guidelines

A consistent naming pattern is one of the most important elements of predictability and discoverability in a managed class library.


2.1.6.1Capitalization Styles

Describes the Pascal case, camel case, and uppercase capitalization styles to use to name identifiers in class libraries.


  • Pascal case


The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized. You can use Pascal case for identifiers of three or more characters.

Example:

BackColor







  • Camel case


The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized.

Example:


backColor





  • Uppercase


All letters in the identifier are capitalized. Use this convention only for identifiers that consist of two or fewer letters.



Example:

Sysetm.IO


System.Web.UI








The following table summarizes the capitalization rules and provides examples for the different types of identifiers:


Identifier

Case

Example

Class

Pascal

AppDomain

Enum type

Pascal

ErrorLevel

Enum values

Pascal

FatalError

Event

Pascal

ValueChange

Exception class

Pascal

WebException

Note   Always ends with the suffix Exception.

Read-only Static field

Pascal

RedValue

Interface

Pascal

IDisposable

Note   Always begins with the prefix I.

Method

Pascal

ToString

Namespace

Pascal

System.Drawing

Parameter

Camel

typeName

Property

Pascal

BackColor

Protected instance field

Camel

redValue

Note   Rarely used. A property is preferable to using a protected instance field.

Public instance field

Pascal

RedValue

Note   Rarely used. A property is preferable to using a public instance field.




2.1.6.2Case Sensitivity


  • Do not use names that require case sensitivity. Components must be fully usable from both case-sensitive and case-insensitive languages.


  • Case-insensitive languages cannot distinguish between two names within the same context that differ only by case. Therefore, you must avoid this situation in the components or classes that you create.


  • Do not create two namespaces with names that differ only by case. For example, a case insensitive language cannot distinguish between the following two namespace declarations.

namespace ee.cummings;

namespace Ee.Cummings;







  • Do not create a function with parameter names that differ only by case. The following example is incorrect.


void MyFunction(string a, string A)





  • Do not create a namespace with type names that differ only by case. In the following example, Point p and POINT p are inappropriate type names because they differ only by case.

System.Windows.Forms.Point p


System.Windows.Forms.POINT p







  • Do not create a type with property names that differ only by case. In the following example,

int Color and int COLOR are inappropriate property names because they differ only by case.

int Color

{

get, set

}


int COLOR

{

get, set

}














  • Do not create a type with method names that differ only by case. In the following example, calculate and Calculate are inappropriate method names because they differ only by case.

void calculate()


void Calculate()








2.1.6.3Abbreviations


  • To avoid confusion and guarantee cross-language interoperation, follow these rules regarding the use of abbreviations:


  • Do not use abbreviations or contractions as parts of identifier names.

Example:


Good:

GetWindow


Not Good:

GetWin









  • Do not use acronyms that are not generally accepted in the computing field.


  • Where appropriate, use well-known acronyms to replace lengthy phrase names. For example, use UI for User Interface and OLAP for On-line Analytical Processing.


  • When using acronyms, use Pascal case or camel case for acronyms more than two characters long. For example, use HtmlButton or htmlButton. However, you should capitalize acronyms that consist of only two characters, such as System.IO instead of System.Io.



  • Do not use abbreviations in identifiers or parameter names. If you must use abbreviations, use camel case for abbreviations that consist of more than two characters, even if this contradicts the standard abbreviation of the word.


2.1.6.4Namespace Naming Guidelines


  • You should use Pascal case for namespaces

  • T

    CompanyName.TechnologyName[.Feature][.Design]


    For example:


    Microsoft.Media


    Microsoft.Media.Design

    he general rule for naming namespaces is to use the company name followed by the technology name and optionally the feature and design as follows.










2.1.6.5Class Naming Guidelines

  • Use a noun or noun phrase to name a class.


  • Use Pascal case.


  • Use abbreviations sparingly.


  • Do not use a type prefix, such as C for class, on a class name. For example, use the class name FileStream rather than CFileStream.


  • Do not use the underscore character (_).


  • Where appropriate, use a compound word to name a derived class. The second part of the derived class's name should be the name of the base class. Example : ApplicationException

public class FileStream


public class Button


public class String









  • Do not use the base word to access base class members unless you wish to resolve a conflict with subclasses member of the same name or when invoking base class constructors.


public class Dog

{

public Dog ( string name )

{ }

virtual public void Bark ( int howLong )

{}

}


public class GermanShepherd : Dog

{

public GermanShepherd( string name ) : base( name )

{}

override public void Bark( int howLong )

{

base.Bark( howLong )

}

}




















2.1.6.6Interface Naming Guidelines


The following rules outline the naming guidelines for interfaces:


  • Name interfaces with nouns or noun phrases, or adjectives that describe behaviour.

Example:

IComponent // noun.

ICustomAttributeProvider //noun.

IPersistable //adjective.







  • Use Pascal case.


  • Use abbreviations sparingly.


  • Prefix interface names with the letter I, to indicate that the type is an interface.


  • Use similar names when you define a class/interface pair where the class is a standard implementation of the interface. The names should differ only by the letter I prefix on the interface name.


  • Do not use the underscore character (_).


  • Always user Interfaces.



Example:

The following are examples of correctly named interfaces.

public interface IServiceProvider


public interface IFormatable








The following code example illustrates how to define the interface IComponent and its standard implementation, the class Component.


public interface IComponent

{

// Implementation goes here.

}


public class Component: IComponent

{

// Implementation code goes here.

}













  • Classes and interfaces should have at least 2:1 ratio of methods to properties.


  • Avoid interfaces with one method.


  • No more than 20 members per interface.


  • Avoid event as interface members.


  • Avoid abstract methods, user interfaces instead.

2.1.6.7Attribute Naming Guidelines


You should always add the suffix Attribute to custom attribute classes.

Example:

public class ObsoleteAttribute{}






2.1.6.8Enumeration Type Naming Guidelines


  • The enumeration (Enum) value type inherits from the Enum Class.

    • Use Pascal case for Enum types and value names.

    • Use abbreviations sparingly.


    • Do not use an Enum suffix on Enum type names.


    • Use a singular name for most Enum types, but use a plural name for Enum types that are bit fields.


    • Always add the FlagsAttribute to a bit field Enum type.


Example:

Good:

public enum Color

{

Red, Green, Blue

}


Not Good:

Public enum Color

{

Red = 1, Green = 2, Blue = 3

}


Specifying type for an enum


Not Good:

public enum Color : long

{

Red, Green, Blue

}























2.1.6.9Static Field Naming Guidelines

  • Naming guidelines for static fields:


    • Use nouns, noun phrases, or abbreviations of nouns to name static fields.


    • Use Pascal case.


    • Do not use a Hungarian notation prefix on static field names.


    • It is recommended that you use static properties instead of public static fields whenever possible.


Example:

public static int Global1 = 100;


public static int Global1 = 200;




2.1.6.10Parameter Naming Guidelines


It is important to carefully follow these parameter naming guidelines because visual design tools that provide context sensitive help and class browsing functionality display method parameter names to users in the designer.


  • Use camel case for parameter names.


  • Use descriptive parameter names. Parameter names should be descriptive enough that the name of the parameter and its type can be used to determine its meaning in most scenarios.


  • Use names that describe a parameter's meaning rather than names that describe a parameter's type. Development tools should provide meaningful information about a parameter's type. Therefore, a parameter's name can be put to better use by describing meaning. Use type-based parameter names sparingly and only where it is appropriate.


  • Do not use reserved parameters.


  • Do not prefix parameter names with Hungarian type notation.


Example: correctly named parameters

Type GetType(string typeName)


string Format(string format, object[] args)









2.1.6.11Method Naming Guidelines

The following rules outline the naming guidelines for methods:


  • Use verbs or verb phrases to name methods.


  • Use Pascal case


Examples: Correctly named methods.


RemoveAll()


GetCharArray()


Invoke()









2.1.6.12Property Naming Guidelines

The following rules outline the naming guidelines for properties:


  • Use a noun or noun phrase to name properties.


  • Use Pascal case.


  • Do not use Hungarian notation.


  • Consider creating a property with the same name as its underlying type.


Example:

Good:


1) public class smapleClass

{

public color BackColor

{

//Code for get and set assessors goes here.

}

}


2) Providing a property with the same name as a type.

public enum Color

{

// Insert code for Enum here.

}

public class Control

{

public Color Color

{

get {// Insert code here.}

set {// Insert code here.}

}

}


Not Good:

public enum Color

{

// Insert code for Enum here.

}

public class Control

{

public int Color

{

get {// Insert code here.}

set {// Insert code here.}

}

}


This is incorrect because the property Color is of type Integer.














































2.1.6.13Event Naming Guidelines


The naming guidelines for events:

  • Use Pascal case.


  • Do not use Hungarian notation.


  • Use an EventHandler suffix on event handler names.


  • Specify two parameters named sender and e.


    • The sender parameter represents the object that raised the event. The sender parameter is always of type object.


    • The state associated with the event is encapsulated in an instance of an event class named e. Use an appropriate and specific event class for the e parameter type.


  • Name an event argument class with the EventArgs suffix.


  • Consider naming events with a verb. For example, correctly named event names include Clicked, Painting, and DroppedDown.


  • Do not use a prefix or suffix on the event declaration on the type. For example, use Close instead of OnClose.


Example: Illustrates an event handler with an appropriate name and parameters.


public delegate void MouseEventHandler(object sender, MouseEventArgs e);







Example: Illustrates a correctly named event argument class.

public class MouseEventArgs : EventArgs

{

int x;

int y;


public MouseEventArgs(int x, int y)

{

this.x = x; this.y = y;

}

public int X { get { return x; } }

public int Y { get { return y; } }

}

















2.1.6.14Delegate Naming Guidelines

The naming guidelines for events:


  • Use Pascal case.


  • Do not use Hungarian notation.


  • Copy a delegate to local variable before publishing to avoid concurrency race condition.


  • Always check a delegate for null before invoking it.


  • Use delegate inference instead of explicit delegate instantiation



delegate void SomeDegate();


public void SomeMethod()

{

//Code goes here.

}


SomeDelegate someDelegate = SomeMethod;











2.1.7Use Early Binding for Better performance


  • Early Binding provides much better performance than late binding.


  • Always specify a data type for variables when they are declared. This provides strong typing of variables for best performance.


Good:

Early Binding


String[] address = null;


Not Good:

Late Binding


Object[] address = null;















2.1.8Returning Values

Try to make the structure of your program match the intent. Example:


if(booleanExpression)

{

return true;

}

else

{

return false;

}

should instead be written as

return booleanExpression;

Similarly,

if(condition)

{

return x;

}

return y;

should be written as

return ((condition) ? x : y);

























2.1.9Statements

2.1.9.1Simple Statements

argv++; /* Correct */

argc--; /* Correct */

argv++; argc--; /* AVOID! */










2.1.9.2Compound Statements


Compound statements are statements that contain lists of statements enclosed in braces

"{ statements }".

  • The enclosed statements should be indented one more level than the enclosing braces.

  • The opening brace should be at the beginning of the line that precedes the compound statement; the closing brace should begin a line and be indented to the opening brace.

  • Braces are used around all statements, even single statements, when they are part of a control structure, such as an if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.

2.1.9.3if, if-else, if else-if else Statements

The if-else class of statements should have the following form:

if(condition)

{

statements;

}



if(condition)

{

statements;

}

else

{

statements;

}


if(condition)

{

statements;

}

else if(condition)

{

statements;

}

else

{

statements;

}






























Note: if statements always use braces {}. Avoid the following error-prone form:

if(condition) /* AVOID! THIS OMITS THE BRACES {}! */

statement;








2.1.9.4for Statements


A for statement should have the following form:


for(initialization; condition; update)

{

statements;

}










An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form:


for(initialization; condition; update)

{

/* No Body */

}










When using the comma operator in the initialization or update clause of a "for" statement, avoid the complexity of using more than three variables.


If needed, use separate statements before the "for" loop (for the initialization clause) or at the end of the loop (for the update clause).


2.1.9.5while Statements

A while statement should have the following form:

while(condition)

{

statements;

}

An empty while statement should have the following form:


while(condition)

{

/* No Body */

}


















2.1.9.6do-while Statements

A do-while statement should have the following form:

do

{

statements;

}

while(condition);












2.1.9.7switch Statements

  • Never use goto unless in a switch statement fall through.


  • Always have a default case in a switch statement that asserts.




A switch statement should have the following form:

switch(condition)

{

case ABC:

statements;

/* falls through */


case DEF:

statements;

break;


case XYZ:

statements;

break;


default:

statements;

break;

}

























2.1.9.8Using Statement

Works with any IDisposable object

Data access classes, streams, text readers and writers, network classes, etc.












Good:

using (Resource res = new Resource()) {

res.DoWork();

}


Not Good:


Resource res = new Resource(...);

try {

res.DoWork();

}

finally {

if (res != null) ((IDisposable)res).Dispose();

}

















String Formats

DATE TIME
How to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method.

Custom DateTime Formatting

There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).

Following examples demonstrate how are the format specifiers rewritten to the output.


// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year
String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24
String.Format("{0:m mm}", dt); // "5 05" minute
String.Format("{0:s ss}", dt); // "7 07" second
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes
String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone

You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeForma­tInfo.DateSepa­rator and DateTimeForma­tInfo.TimeSepa­rator.


// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)

Here are some examples of custom date and time formatting:


// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt); // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt); // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt); // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt); // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

Standard DateTime Formatting

In DateTimeForma­tInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.

Following table shows patterns defined in DateTimeForma­tInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.

Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
r, R RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTi­mePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u UniversalSorta­bleDateTimePat­tern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
(*) = culture independent

Following examples show usage of standard format specifiers in String.Format method and the resulting output.


String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt); // "3/9/2008" ShortDate
String.Format("{0:T}", dt); // "4:05:07 PM" LongTime
String.Format("{0:D}", dt); // "Sunday, March 09, 2008" LongDate
String.Format("{0:f}", dt); // "Sunday, March 09, 2008 4:05 PM" LongDate+ShortTime
String.Format("{0:F}", dt); // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt); // "3/9/2008 4:05 PM" ShortDate+ShortTime
String.Format("{0:G}", dt); // "3/9/2008 4:05:07 PM" ShortDate+LongTime
String.Format("{0:m}", dt); // "March 09" MonthDay
String.Format("{0:y}", dt); // "March, 2008" YearMonth
String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123
String.Format("{0:s}", dt); // "2008-03-09T16:05:07" SortableDateTime
String.Format("{0:u}", dt); // "2008-03-09 16:05:07Z" UniversalSortableDateTime

INTEGER
Integer numbers can be formatted in .NET in many ways. You can use static
method String.Format or instance method int.ToString. Following examples shows how to align numbers (with
spaces or zeroes), how to format negative numbers or how to do custom formatting
like phone numbers.

Add zeroes before number

To add zeroes before a number, use colon separator „:“ and write as many zeroes as you want.


String.Format("{0:00000}", 15); // "00015" String.Format("{0:00000}", -15); // "-00015"

Align number to the right or left

To align number to the right, use comma „,“ followed by a number of characters. This alignment option must be before the colon separator.


String.Format("{0,5}", 15); // " 15" String.Format("{0,-5}", 15); // "15 " String.Format("{0,5:000}", 15); // " 015" String.Format("{0,-5:000}", 15); // "015 "

Different formatting for negative numbers and zero

You can have special format for negative numbers and zero. Use semicolon separator „;“ to separate formatting to two or three sections. The second section is format for negative numbers, the third section is for zero.


String.Format("{0:#;minus #}", 15); // "15" String.Format("{0:#;minus #}", -15); // "minus 15" String.Format("{0:#;minus #;zero}", 0); // "zero"

Custom number formatting (e.g. phone number)

Numbers can be formatted also to any custom format, e.g. like phone numbers or serial numbers.


String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456" String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551"

DOUBLE

The following examples show how to format float numbers to string in C#. You can use static method String.Format or instance methods double.ToString and float.ToString.

Digits after decimal point

This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.


// just two decimal places String.Format("{0:0.00}", 123.4567); // "123.46" String.Format("{0:0.00}", 123.4); // "123.40" String.Format("{0:0.00}", 123.0); // "123.00"

Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.


// max. two decimal places String.Format("{0:0.##}", 123.4567); // "123.46" String.Format("{0:0.##}", 123.4); // "123.4" String.Format("{0:0.##}", 123.0); // "123"

Digits before decimal point

If you want a float number to have any minimal number of digits before decimal point use N-times zero before decimal point. E.g. pattern „00.0“ formats a float number to string with at least two digits before decimal point and one digit after that.


// at least two digits before decimal point String.Format("{0:00.0}", 123.4567); // "123.5" String.Format("{0:00.0}", 23.4567); // "23.5" String.Format("{0:00.0}", 3.4567); // "03.5" String.Format("{0:00.0}", -3.4567); // "-03.5"

Thousands separator

To format double to string with use of thousands separator use zero and comma separator before an usual float formatting pattern, e.g. pattern „0,0.0“ formats the number to use thousands separators and to have one decimal place.


String.Format("{0:0,0.0}", 12345.67); // "12,345.7" String.Format("{0:0,0}", 12345.67); // "12,346"

Zero

Float numbers between zero and one can be formatted in two ways, with or without leading zero before decimal point. To format number without a leading zero use # before point. For example „#.0“ formats number to have one decimal place and zero to N digits before decimal point (e.g. „.5“ or „123.5“).

Following code shows how can be formatted a zero (of double type).


String.Format("{0:0.0}", 0.0); // "0.0" String.Format("{0:0.#}", 0.0); // "0" String.Format("{0:#.0}", 0.0); // ".0" String.Format("{0:#.#}", 0.0); // ""

Align numbers with spaces

To align float number to the right use comma „,“ option before the colon. Type comma followed by a number of spaces, e.g. „0,10:0.0“ (this can be used only in String.Format method, not in double.ToString method). To align numbers to the left use negative number of spaces.


String.Format("{0,10:0.0}", 123.4567); // " 123.5" String.Format("{0,-10:0.0}", 123.4567); // "123.5 " String.Format("{0,10:0.0}", -123.4567); // " -123.5" String.Format("{0,-10:0.0}", -123.4567); // "-123.5 "

Custom formatting for negative numbers and zero

If you need to use custom format for negative float numbers or zero, use semicolon separator;“ to split pattern to three sections. The first section formats positive numbers, the second section formats negative numbers and the third section formats zero. If you omit the last section, zero will be formatted using the first section.


String.Format("{0:0.00;minus 0.00;zero}", 123.4567); // "123.46" String.Format("{0:0.00;minus 0.00;zero}", -123.4567); // "minus 123.46" String.Format("{0:0.00;minus 0.00;zero}", 0.0); // "zero"

Some funny examples

As you could notice in the previous example, you can put any text into formatting pattern, e.g. before an usual pattern „my text 0.0“. You can even put any text between the zeroes, e.g. „0aaa.bbb0“.


String.Format("{0:my number is 0.0}", 12.3); // "my number is 12.3" String.Format("{0:0aaa.bbb0}", 12.3); // "12aaa.bbb3"


Align String with Spaces [C#]

This example shows how to align strings with spaces. The example formats text to table and writes it to console output.

To align string to the right or to the left use static method String.Format. To align string to the left (spaces on the right) use formatting patern with comma (,) followed by a negative number of characters: String.Format(„{0,–10}“, text). To right alignment use a positive number: {0,10}.

Following example shows how to format text to the table. Values in the first and second column are aligned to the left and the third column is aligned to the right.

[C#]
Console.WriteLine("-------------------------------"); Console.WriteLine("First Name | Last Name | Age"); Console.WriteLine("-------------------------------"); Console.WriteLine(String.Format("{0,-10} | {1,-10} | {2,5}", "Bill", "Gates", 51)); Console.WriteLine(String.Format("{0,-10} | {1,-10} | {2,5}", "Edna", "Parker", 114)); Console.WriteLine(String.Format("{0,-10} | {1,-10} | {2,5}", "Johnny", "Depp", 44)); Console.WriteLine("-------------------------------"); Output string:
------------------------------- First Name | Last Name | Age ------------------------------- Bill | Gates | 51 Edna | Parker | 114 Johnny | Depp | 44 -------------------------------

Indent String with Spaces [C#]

This example shows how to indent strings using method for padding in C#. To repeat spaces use method String.PadLeft. If you call „hello“.PadLeft(10) you will get the string aligned to the right: „ hello“. If you use empty string instead of the „hello“ string the result will be 10× repeated space character. This can be used to create simple Indent method.

The Indent method:

[C#]
public static string Indent(int count) { return "".PadLeft(count); }

Test code:

[C#]
Console.WriteLine(Indent(0) + "List"); Console.WriteLine(Indent(3) + "Item 1"); Console.WriteLine(Indent(6) + "Item 1.1"); Console.WriteLine(Indent(6) + "Item 1.2"); Console.WriteLine(Indent(3) + "Item 2"); Console.WriteLine(Indent(6) + "Item 2.1");

Output string:

List Item 1 Item 1.1 Item 1.2 Item 2 Item 2.1

How to prevent our .NET DLL from decompilation

Scenario: By design, .NET embeds rich Meta data inside the executable code using MSIL. Any one can
easily decompile your DLL back using tools like ILDASM (owned by Microsoft) or Reflector for
.NET which is a third party.
                Secondly, there are many third party tools, which make this
decompiling process int a single click. So any one can easily look in to your assemblies and reverse
engineer them back in to actual source code and understand some real good logic, which can
make it easy to crack your application.

Here the solution: You can stop this reverse engineering by using "obfuscation". It is a
technique, which will foil the decompilers. Many third parties (XenoCode, Demeanor for .NET)
provide .NET obfuscation solution. Microsoft includes one that is Dotfuscator Community
Edition with Visual Studio.NET.

Listen to nirmaln - sakara - playlist audio songs at MusicMazaa.com