Check if a number is odd or even in c#

Ver os números primos em c#

static void CheckOddEven(int num)
{
  if (num % 2 == 0)
  { 
    Console.Write("\nYour number is even.\n");
  }  
  else
  {  
    Console.Write("\nYour number is odd.\n"); 
  }
}


static void Main(string[] args)
{ 
  int num = 0;
  string answer = "Y";

  while(answer== "Y")
  {
     Console.Write("Please enter a number and I will tell you whether it is odd or even.\n");

     //convert input to int
     num = int.Parse(Console.ReadLine());

     //call method to check if the number is odd or even
     CheckOddEven(num);

     //ask if the user wants to continue or quit
     Console.Write("Do you wanna check another number? Y/N\n");
    answer= Console.ReadLine().ToUpper();
   }
}
Read More... Check if a number is odd or even in c#

Convert a phrase to binary in c#

Para converter uma frase para binario em c#


static void Main(string[] args)
        {
            String str "The phrase to be converted!!!";


            Console.WriteLine(String2Binary(str));


            Console.ReadKey();
        }


        private static String String2Binary(String str)
        {
            String return = null;


            foreach (var letter in str)
                return +(Convert.ToString(letter,2)).PadLeft(8'0') + " ";

            return return;
        }
Read More... Convert a phrase to binary in c#

Latex Parte III


Modifying text styles
To modifying some text, to make it italic, bold..., we need to add a tag, like in the next examples.
  • To insert bold text, use \textbf{text here}
  • To insert italic text, use \emph{text here}
  • To insert monospace text, use \texttt{text here} 
  • To use verbatim text within a sentence, use \verb|your text here|.Note: any delimiter can be used.



Figures and tables
Figures and tables are LaTeX environments, however the final position of the elements depends on the latex's style algorithm, thats why they are called float elements.
Figures
To insert a figure, use
\begin{figure}[hbtp]
\caption{Figure name}
\begin{center}
\includegraphics{filename.pdf}
\end{center}
\label{your-reference-key}
\end{figure}
In the above markup,
  • \begin{figure} tells that is a figure environment
  • [hbtp] tells how LaTeX will place the figure :
    • (here (h), bottom (b), top(t), page(p)). 
    • If the current space where the figure is called, don't have space, it will be placed in the next page, if you want to force the location, simple choose \begin{figure}[h], omitting b, p and t. The order in which h,b,t and p are specified determines where LaTeX tries to place the float first.
  • \caption{Figure name} name of the figure
  • \begin{center} tells to center the figure in the document. Note: don't forget to close the tag center.
  • \includegraphics{…} location of the file
  • \label{your-reference-key} is a label that you can use to refer to the figure in the text. For example, if you label your figure “fig1″ then you can reference it later on by typing \ref{fig1}


Tables
A floated table in LaTeX consists of two environments: table, the actual floated entity in the text, and tabular, the data contained in the table. For example, 




\begin{tabular}{|c|c|}
\hline BIT & Significado se igual a 1 \\
\hline URG & O campo Urgent Pointer È v·lido \\
\hline ACK & O campo Acknowledgement Number È v·lido \\
\hline PSH & Este segmento pede um push \\
\hline RST & Reinicia a comunicaÁ„o \\
\hline SYN & Sincroniza os n˙meros de sequÍncia \\
\hline FIN & O emissor chegou ao fim do fluxo de informaÁ„o \\
\hline
\end{tabular}



everything except the code between \begin{tabular} … \end{tabular} is the same as the figure. Here’ s how the
tabular environment works:
  • \begin{tabular}{c|cc} tells LaTeX to start a new tabular environment with two centered columns. The bar (“|”) after the first “c”, tells that have a vertical border. We can use {lcrr} to create columns: 
    • the first left aligned, the second centered, and the third and fourth right aligned
  • The table cells are separated by a “&” and the table rows are separated by a “\\”

This is not the the table example, but can be also used in the tables.
  • The \hline creates a horizontal line
  • \multicolumn{2}{c}{Example} creates a row that spans all two columns, and gonna be centered, and contains the text “Example”
  • There are more options, but this is allmost what you need to create tables.





Annotations
In LateX we can import some annotations, footnotes, references, table of contents, and bibliographies.
Footnotes
To insert a footnote, we just have to insert  \footnote{Footnote text here}.
Cross references
To insert a reference on a table or figure, we just have to type \ref{your-reference-key} where “your-reference-key” is the argument to the \label{your-reference-key} command.




Table of contents
To insert a table of contents, simply put \tableofcontents at the beginning of your document. (You must run LaTeX twice to get the table of contents and references to work correctly.

Bibliography
To create a bibliography,we just have to use the next form:
\begin{thebibliography}{99}
….
\bibitem{key1} Disarray, General. 2006. “\LaTeX{}: from beginner to \TeX pert.” \emph{General Disarray Blog}. Available online at \textt{http://generaldisarray.wordpress.com}. ….
\end{thebibliography}
We have to type he bibliography entry, and to refer a item we must use \cite{key}. The {99} tells that the maximum is 99 entries in the bibliography.
To build the bibliography we can use bibTex, is more efficient to build one, so we dont have to hardcode the references.

An website that helps a lot in latex is http://aprendolatex.wordpress.com/, is in portuguese, but have a lots of exemples to improve your latex documents


Sources: http://generaldisarray.wordpress.com/2006/04/20/latex-from-beginner-to-texpert/

Read More... Latex Parte III

Latex Part II

LaTeX commands

LaTeX commands generally begin with a backslash and take the form \command[options]{argument}. For example,
\section{Introduction}
This will create a section, with the name Introduction.
If we want to insert a coment, we just need to insert a '%' character, and everything you type to the end of the line will be commented.
To insert the '%' , just insert a backslash: \%


The preamble
Everything we type before the line “\begin{document}” is part of the preamble. The typical preamble look like this:

\documentclass{article}
\usepackage{graphicx}
\title{Test}
\author{Test}
\date{}
In the example above:

  • \documentclass{article} tells LaTeX that the document is an article. Other classes include book, letter and slides
  • \usepackage{graphicx} tells LaTeX to use the graphicx package, which allow users to insert graphics in the documents
  • \title{} and \author{} define the title and author
  • \date{} tells LaTeX to write the today date. \date{June 2010} would print “June 2010? as the date.
The \documentclass{} command can contain some options, for example, \documentclass[11pt,twocolumn]{article} would organize body of the document into two columns and the options are separated by a comma. Other options include:

  • oneside or twoside – change margins for a one or two-sided document
  • landscape – change the document from landscape to portrait
  • titlepage or notitlepage – define whether there is a separate title page, or if the title, author and date info are show at the top of the article

Document structure
A document’s structure is defined using \section{} commands. LaTeX is based on well-structured documents. The structure tags are :

  • \section{Name}
  • \subsection{Name}
  • \subsubsection{Name}
  • \paragraph{Name}
If you want to insert a unnumbered section, you can use the command \section*{Name}. In the next section, the numbering will continue as normal.
The \paragraph{}is used if you want to insert a heading for a paragraph.

The next image will show the comands explained before:



Lists items

If we want to itemize(create bulleted) or enumerate(numbered lists), just do as we do in the following example:

To itemize:

\begin{itemize}
\item First thing
\item Second thing
\item Third thing
\end{itemize}

To enumerate:


\begin{enumerate}
\item First numbered thing
\item Second numbered thing
\end{enumerate}


The graphicx package
The graphicx package allows you to insert images into the document. To use it, we have to import it, to do that we just type the command \usepackage{graphicx} in your document preamble. After that, to insert a image we just need to type:


\includegraphics[options]{filename.png}
The images supports many filetypes, including PDF, PNG and JPG. The options include:


  • width=Xin
  • height=Xin
  • scale=X (where x is between 0 and 1)

The geometry package
Formating in latex can be easy, but changing the defaults formats can be a little bit difficult. The geometry package can changes somes aspects of the document, for example if we want to change the margin to 1, we just need to type the next command:


\usepackage[margin=1in]{geometry}

Continues in next post.

An website that helps a lot in latex is http://aprendolatex.wordpress.com/, is in portuguese, but have a lots of exemples to improve your latex documents


Sources: http://generaldisarray.wordpress.com/2006/04/20/latex-from-beginner-to-texpert/

Read More... Latex Part II

Latex Part I

LaTeX commands

LaTeX commands generally begin with a backslash and take the form \command[options]{argument}. For example,
\section{Introduction}
This will create a section, with the name Introduction.
If we want to insert a coment, we just need to insert a '%' character, and everything you type to the end of the line will be commented.
To insert the '%' , just insert a backslash: \%


The preamble
Everything we type before the line “\begin{document}” is part of the preamble. The typical preamble look like this:

\documentclass{article}
\usepackage{graphicx}
\title{Test}
\author{Test}
\date{}
In the example above:


  • \documentclass{article} tells LaTeX that the document is an article. Other classes include book, letter and slides
  • \usepackage{graphicx} tells LaTeX to use the graphicx package, which allow users to insert graphics in the documents
  • \title{} and \author{} define the title and author
  • \date{} tells LaTeX to write the today date. \date{June 2010} would print “June 2010? as the date.
The \documentclass{} command can contain some options, for example, \documentclass[11pt,twocolumn]{article} would organize body of the document into two columns and the options are separated by a comma. Other options include:

  • oneside or twoside – change margins for a one or two-sided document
  • landscape – change the document from landscape to portrait
  • titlepage or notitlepage – define whether there is a separate title page, or if the title, author and date info are show at the top of the article

Document structure
A document’s structure is defined using \section{} commands. LaTeX is based on well-structured documents. The structure tags are :

  • \section{Name}
  • \subsection{Name}
  • \subsubsection{Name}
  • \paragraph{Name}
If you want to insert a unnumbered section, you can use the command \section*{Name}. In the next section, the numbering will continue as normal.
The \paragraph{}is used if you want to insert a heading for a paragraph.

The next image will show the comands explained before:



Lists items


If we want to itemize(create bulleted) or enumerate(numbered lists), just do as we do in the following example:

To itemize:

\begin{itemize}
\item First thing
\item Second thing
\item Third thing
\end{itemize}

To enumerate:

\begin{enumerate}
\item First numbered thing
\item Second numbered thing
\end{enumerate}


The graphicx package
The graphicx package allows you to insert images into the document. To use it, we have to import it, to do that we just type the command \usepackage{graphicx} in your document preamble. After that, to insert a image we just need to type:

\includegraphics[options]{filename.png}
The images supports many filetypes, including PDF, PNG and JPG. The options include:

  • width=Xin
  • height=Xin
  • scale=X (where x is between 0 and 1)


The geometry package
Formating in latex can be easy, but changing the defaults formats can be a little bit difficult. The geometry package can changes somes aspects of the document, for example if we want to change the margin to 1, we just need to type the next command:

\usepackage[margin=1in]{geometry}

Continues in next post.

An website that helps a lot in latex is http://aprendolatex.wordpress.com/, is in portuguese, but have a lots of exemples to improve your latex documents


Sources: http://generaldisarray.wordpress.com/2006/04/20/latex-from-beginner-to-texpert/

Read More... Latex Part I

Sexta feira... WTF




Um video para descansar...se conseguirem :P

" Camila e mariana Davalos "
Read More... Sexta feira... WTF

CShell script - Delete accounts in linux from file

Next script delete account in linux from a file



#! /usr/bin/perl -w 
use strict;

my $i=""; 
my $FInput; 
my @arrContas=();

if(@ARGV != 1)
{
    print("Sintaxe: ./delete_Accounts.pl \n"); exit 1;
}

if(!open($FInput,"$ARGV[0]")) 
{
    print("Error reading the input file\n"); exit 1;
}

@arrContas=<$FInput>;
close($FInput);
for $i (@arrContas) 
{
     chomp($i); 
     `userdel --remove $i`; 
     print("Account $i sucessful deleted\n");
}
Read More... CShell script - Delete accounts in linux from file

Script to create users in linux



This script create accounts in linux.
the password is the same as the user.


#! /usr/bin/perl -w 
use strict;


my $i=””; 
my $FInput; 
my @arrContas=(); 
my $strEncPwd=""; 
my $strSalt="LX";


if(@ARGV != 1)
{
      print("Sintaxe: ./CreateAccounts.pl \n"); exit 1;
}

if(!open($FInput,"$ARGV[0]"))
{
     print("Error reading the input file\n"); exit 1;
}

@arrContas=<
$FInput>;
close($FInput);

for $i (@arrContas)
 {
      chomp($i); 
      $strEncPwd=crypt($i,$strSalt); 
      `useradd -p '$strEncPwd' -m $i`; 
      print("Account $i sucessful created\n");
}
Read More... Script to create users in linux

Comandos Linux

$ ls -la `which ps`
# Mostra a listagem longa do ficheiro do comando ps.

$ id `whoami`
# Mostra a informação sobre o utilizador que efectuou o login.



$ comando1 $(comando2 [-opções])
O comando2 é executado e é o parâmetro de entrada do comando1.

Exemplos:
$ ls -la $(which ps)
# Mostra a listagem longa do ficheiro do comando ps. $ id $(whoami)
# Mostra a informação sobre o utilizador que efectuou o login.



-Cut
Comandos de manipulação de texto





$ cut ficheiro
Permite cortar partes de um ficheiro.
Opções:
[-f] [-d] [-c]
especifica os campos a devolver; especifica o delimitador de campo (por omissão é o TAB); caracteres a devolver.

Exemplo:
$ cut –f1 –d: /etc/passwd
# Mostrar todos os logins registados na máquina (campo número 1)



-Paste
$ paste ficheiro1 ficheiro2 ficheiro3 ...
Junta o conteúdo de ficheiros (pega na 1-a linha de ficheiro1, na 1-a linha de ficheiro2, ..., na 1-a linha de ficheiro n e junta-as numa só, com os campos separados por TAB.

Opções:
[-d]            especifica o delimitador de campo (por omissão é o TAB); [-s]            processa ficheiros de forma sequencial (e não em paralelo).


-
Translate(tr)
$ tr conjunto1 conjunto2
O comando tr (translate) permite a conversão de caracteres do “conjunto1” para o “conjunto2”. Dado que, por omissão, o tr manipula o stdin e o stdout, torna-se necessário recorrer a redireccionamento de entrada/saída caso se pretenda efectuar a operação em ficheiros.

Opções:
[-d]            (delete) apaga caracteres em vez de proceder à substituição; [-s]            (squeeze) elimina repetições.

Exemplos:
$ tr ‘a’ ‘A’ < input.txt > output.txt
# Converte todos os ‘a’ em “A”

 $ tr [a-z] [A-Z] < input.txt > output.txt
# Converte todos as minúsculas em maiúsculas




-Grep
Comandos de extracção de texto
$ grep [opt] [] Procura expressões (palavras, etc.) num ficheiro.

Opções:
[-i]            ignora maiúsculas e minúsculas; [-c]            número de linhas que verificam a condição; [-n]            devolve os números das linhas (bem como as próprias linhas) que verificam a condição; [-v]            inverte a pesquisa, exibindo apenas as linhas que não verificam a condição.

Exemplos:
$ ps aux | grep root
# devolve as linhas de “ps” que contém a palavra “root”

$ ps aux | grep $(whoami)
# devolve as linhas de “ps” que contém o login de quem executa o comando



- Expressões regulares básicas
Em Unix (e em muitos outros ambientes), as expressões regulares (muitas vezes designadas por “regex” na literatura anglo-saxónica) são uma forma poderosa de definir padrões. Iremos de seguida abordar o mecanismo simples de “âncoras”.
Âncoras: permitem indicar que o padrão a pesquisar se encontra no início ou no fim.
O grep (e outros comandos com suporte para regex) suporta as seguintes âncoras:

Opções:
[^]            início de linha; [$]            fim de linha.
Exemplos:
$ ps aux | grep ^root
# devolve as linhas do “ps aux” que **comecem** por “root”

$ seq 100 | grep 0$
# devolve os números de 0 a 99 que **terminam** em 0




Comandos de “message digest”
A designação “message digest” (algoritmos de hash) refere-se à criação de um identificador unívoco (muitas vezes em formato hexadecimal) para a representação do conteúdo de um ficheiro. Existem vários algoritmos de hash, desde o MD5 (Message Digest) e o SHA (Secure Hash Algorithm). Para além da aplicação em criptografia, os messages digests podem ser empregues para a detecção de ficheiros idênticos. No Linux existem os seguintes utilitários para o cálculo de message digests:
md5sum •            sha1sum (e outros tais como “sha224sum”, “sha256sum”)

Exemplos:
$ who > who.txt $ md5sum who.txt
# calcula o “md5sum” de “who.txt”~

$ md5sum $(ls)
# calcula o md5sum de todos os ficheiros do directório corrente

$ ps aux | sha1sum
# calcula o sha1sum da saída produzida pelo comando “ps aux”



Extracção de conteúdos em páginas “html”
Muitas vezes torna-se necessário a extracção de conteúdos em páginas online que se encontram em formato HTML. A extracção da informação pretendida faz-se muitas vezes com recurso a heurísticas.

- Utilitáriowget
$ wget [opt] url
# descarrega (download) conteúdos online via http, ftp ou https O utilitário wget permite o acesso a conteúdos online (através de http, https e ftp).

Opções:
[-c]            continua operação de descarregamento (anteriormente interrompida); [-O ] grava conteúdo para “ficheiro”.

Exemplos:
# Obtém e grava o conteúdo da página inicial de http://informatictips.blogspot.com/

$ wget http://tinyurl.com/ –O osstats.html
# Obtém e grava para “osstats.html” o conteúdo do URL http://tinyurl.com/
Read More... Comandos Linux

Several Linq Examples

Next is a website that will help you daily, when you use linq in your applications

http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
Read More... Several Linq Examples

CSS stylesheet

Read More... CSS stylesheet

Linq - Return a list with a specific size

public static List ReadUsersNotVisitorByPaging(int currentPage, int pagesize, out int totalPages, out int totalItems) {
List fullList = (from usr in ReadUsers().ToList()
                                                        where usr.Removed == false
                                                        orderby usr.Name
                                                        select usr).ToList();

            totalItems = fullList.Count;
            if (totalItems < pagesize)
                totalPages = 1;

            else
                if ((fullList.Count % pagesize) == 0)
                    totalPages = fullList.Count / pagesize;
                else
                    totalPages = (fullList.Count / pagesize) + 1;

            //calcular o numero de items para fazer skip
            int nextpage = 0;
            if ((currentPage - 1) != 0)
                nextpage = pagesize * (currentPage - 1);

            List filterList = (from p in fullList.Skip(nextpage).Take(pagesize) select p).ToList();

Return filterList;
}

This return a list filter by size, is usefull for paging.


Read More... Linq - Return a list with a specific size

Random sort list with LINQ

LINQ (Language Integrated Query) is a one of very useful feature of .net 3.5 framework. This allows you to query objects and perform complex operations simply and efficiently. There are lots of trick which can be used with the help of LINQ. In this article I am explaining how can we random sort a List using LINQ

Random Sort

Consider the below Employee class:
public class Employee
{
    public int Id
    {
        get;
        set;
    }
    public string Name
    {
        get;
        set;
    }
}
This is how you can randomly sort the List object:
List list = new List();



list.Add(new Employee { Id = 1, Name = "Luis" });
list.Add(new Employee { Id = 2, Name = "Vieira" });
list.Add(new Employee { Id = 3, Name = "Joana" });
list.Add(new Employee { Id = 4, Name = "Laura" });
list.Add(new Employee { Id = 5, Name = "Antonio" });
list.Add(new Employee { Id = 6, Name = "Toino" });
list.Add(new Employee { Id = 7, Name = "Lara" });
list.Add(new Employee { Id = 8, Name = "Filipe" });
list.Add(new Employee { Id = 9, Name = "Miguel" });

list = list.OrderBy(emp => Guid.NewGuid()).ToList();




From: http://www.dailycoding.com/Posts/random_sort_a_list_using_linq.aspx
Read More... Random sort list with LINQ

C# Tricks and tips


As the title indicates, this article will be about C# tips and tricks. I'll cover some of the C# 3.0 language features, explore productivity gains with the Visual Studio 2008 C# IDE, and mention a couple of handy Visual Studio plug-ins that may be of interest. This deviates from the traditional articles I've presented in the past and will hopefully provide some value in its own way.

C# 3.0 Background
C# 3.0 was released as a part of the Microsoft .NET 3.5 Framework. The main purpose was to provide a foundation for Language INtegrated Query (LINQ) to provide unified data access capability. Each enhancement also can be used on its own. Here is a list of the features you'll cover and learn some related tips:
   Automatically implemented properties
   Using Keyword
   Object and collection intitializers
   Local type inference
   Extension methods

Automatically Implemented Properties
Automatically implemented properties offer a concise syntax for implementing property accessors that get and set a private field. They create a field backed property without requiring you to actually create a field. The compiler automatically generates it for you at compile time. They can be used only for simple get and set of properties because there is no body and no field. No property body means no breakpoints or validation logic can be used. No field means no default value. Typing "prop [tab][tab]" is the Visual Studio code snippet for producing an automatically implemented property. This can make your code much more concise. A classic example of a field back property might look something like the code below.
private int myProperty = 0;
public int MyProperty
{
   get { return this.myProperty; }
   set { this.myProperty = value; }
}

A simpler example that uses automatically implemented properties for the same field is below.
public int MyProperty
{
   get; set;
}
However, it is important not to be too lazy and use this haphazardly. Examine the code below where you define a Customer class. Take note of the CustomerKey property that is defined. Typically, such a key field is a readonly item that is set once and doesn't change. When taking a shortcut using automatically implemented properties, it allows for undesired behavior with the code.
class Customer
{
   public string CustomerKey { get; set; }
   public string ContactName { get; set; }
   public string City { get; set; }
}
You might try refactoring the code to have a private set and use a constructor to control the value. Although this does protect the field from the outside, it could still be altered internally to the class.
class Customer
{
   public Customer(string customerKey)
   {
      CustomerKey = customerKey;
   }

   public string CustomerKey { get; private set; }
   public string ContactName { get; set; }
   public string City { get; set; }
}
In reality, an automatically implemented property probably isn't appropriate for the CustomerKey property and the code should look like the example below. The class in question in this example is pretty simple, but it illustrates the point that the automatically implemented properties should be applied liberally, but with caution.
class Customer
{
   public Customer(string customerKey)
   {
      this.CustomerKey = customerKey;
   }
   private readonly string customerKey;
   public string CustomerKey
   {
      get return this.customerKey;
   }

   public string ContactName { get; set; }
   public string City { get; set; }
}

using Keyword
There is a prior article that is dedicated solely to the using keyword. Even though this isn't necessarily new, it is worth mentioning and at least pointing to that article for more detail. The main benefit is that it can be used to implement try ... finally behavior and offers an automatic cleanup of disposable types. There is a lot of value to be had by implementing this in your code whenever objects such as DataReader are used to ensure that connections will be properly disposed when complete.
using (IDataReader reader = provider.ExecuteReader(dataCmd))
{
   // ...
}


Local Type Inference
Local type inference was also the subject of another prior article, but again is worth mentioning here as it is very handy to have a solid understanding. You define variables with the var keyword and the compiler will figure out the type for you at compile time and replace it. It is great for results from query expressions as show in the example below. It may appear that it is untyped or even give the impression it is a variant. It is not. It is a strongly typed object whose type is set at compile time.
var i = 5;
int i = 5;

string[] words = { "cherry", "apple", "blueberry" };

var sortedWords =
   from w in words
   orderby w
   select w;

Object and Collection Initializers
Initializers introduce a concise syntax that combines object creation and initialization in a single step. It even allows for parentheses to be optional for paramaterless constructors as you'll see in the first line of the example below.
Point p = new Point { X=3, Y=99 };

Student myStudent = new Student() {
   Name   = "John Doe",
   Class  = "Senior",
   School = "Carmel" };

This functionality is great for demos where you are building collections of objects to do things like LINQ queries against. However, I caution you to consider real life initialization of large sets of data and whether code over a database is the proper place to store such information.
Initializers work very well with constructors. The example below shows an instance where a parameterized constructor is called along with remaining properties initialized. The constructor should commonly take all of the parameters so it isn't an ideal setup, but it illustrates the point well.
class Customer
{
   public Customer(string customerKey) { ... }
   public string CustomerKey { get { ... } }
   public string ContactName { get; set; }
   public string City { get; set; }
}

var c = new Customer("MARKS"){
   ContactName = "Mark Strawmyer",
   City = "Indianapolis"
}
Extension Methods
Extension methods allow you to create new functionality on existing types. Even if the types are sealed. They are declared like static methods and called like instance methods. They are valid for use on interfaces or constructed types. The trailing sample code illustrates the use of extension methods to add a Triple and Half method on the decimal type.
static class ExtensionSample
{
   public static decimal Triple( this decimal d ) { return d*3; }
   public static decimal Half( this decimal d ) { return d / 2; }
}

decimal y = 14M;
y = y.Triple().Half();
Extension methods can be a very powerful tool. They can also be a very annoying tool if not used with some care. You should consider a separate namespace to allow them to be optional to the other developers that may be working within your codebase. Resist the temptation to put them on all objects by extending the object class. For consistency you should also make them behave like other instance methods.
The following code sample illustrates very bad form that should not be practiced. The namespace is System, which means the scope of this extension is any code that comes in contact with it. It extends ALL objects. It also does not behave like a normal instance method. Normally calling an instance method on a null object would result in a NullReferenceException and not a Boolean true or false value. This is a code example of what is not advisable.
namespace System
{
   public static class MyExtensions
   {
      public static bool IsNull(this object o) {
         return o == null;
      }
   }
}

while (!myObject.IsNull()) { ... }

LINQ Performance Tip
I'm not going to cover much on LINQ here as those are articles in and of themselves. Here is a LINQ performance tip that I experienced first hand on a project. Consider carefully the use of Table.ToList().Find(). Table.Where() is commonly a better option. ToList().Find() returns all records from a table and then runs the filter in memory. Table.Where() is performed in SQL and returns only the rows requested.
An additional tip is there is a handy tool known as LINQPad that allows you to perform interactive queries of databases using LINQ. It is a code snippet IDE that will execute any C# expression or statement block, which is very handy for testing out LINQ.

Productivity Gains with the Visual Studio C# IDE
The Visual Studio IDE offers a vast number of productivity gains when you have the IDE configured with a C# developer profile.
   Coding shortcuts
   Clipboard ring
   Code snippets
   Visual Studio 2008 Service Pack 1
Coding Shortcuts
Visual Studio is chalk full of hundreds of coding shortcuts. I'll call out a few of the ones that I've found to be most helpful.
   Incremental search: Ctrl + I to begin incremental search. You'll notice the mouse pointer will change to binoculars with a downward arrow. Start typing to find a match within the current code file. Ctrl + I again will find the next occurrence in the code file. Ctrl + Shift + I will reverse direction and search upward in the code file.
   Repeat search: F3 to search again for the last item in the Find dialog box. Ctrl + F3 will behave similarly except will include the Match case option.
   Commenting and uncommenting code: Ctrl + K followed by Ctrl + C will comment out the current line or selected block of code. Ctrl + K followed by Ctrl + U will uncomment the current line or selected block of code.
   Indenting: Ctrl + K followed by Ctrl + F will cause Visual Studio to automatically format your code according to the editor formatting rules.
Karen Liu's blog (Microsoft's C# IDE Program Manager) has many, many more useful shortcuts available.
Clipboard Ring
Have you experienced a scenario when you have you cut or copied a line of code only to discover another line of code that you also cut or copy? The original code copied is then lost from the copy buffer and you must undo changes to get back to the first change. The clipboard ring can be your new best friend if this is a common occurrence for you. You cut or copy multiple lines of code independently. Ctrl + Shift + V will allow you to cycle through the code in the clipboard ring. If you are going to use the clipboard ring it is a good idea to consider Tools > Options > Text Editor > All Languages > General and set the "Apply Cut or Copy commands to blank lines when there is no selection" option.
Code Snippets
Code snippets are ready-made task-oriented blocks of code. Visual Studio includes a number of default snippets that are activated by typing a specific sequence of keys followed by [tab][tab] to cause the Visual Studio IDE to engage. In addition to typing the snippet in code, you can right-click at the desired location and choose Insert Snippet or Surround With. Here is a very small sampling of what is available.
   Tryf = try and finally block
   Prop = property with get and set accessor
   Switch = switch statement with default
Microsoft has a number of additional code snippets available for download. Additionally, there is a free Snippet Designer that allows you to easily create or modify your own code snippets.
Visual Studio 2008 Service Pack 1
Visual Studio 2008 Service Pack 1 is full of all kinds of goodies that make it worth downloading and installing. The download will take a while, but definitely worth it. Here is a very limited taste of what is included.
   Solution-wide TODO tasks.
   Compiler error "squiggles" on the fly when editing.
   Step into specific that allows you to step in to a particular method call when you have code that has several nested calls as a part of a single statement.
   Many, many, more
Summary
You have now seen various tips and tricks related to items within C# 3.0 and the Visual Studio 2008 C# IDE. Hopefully this has provided you some useful insight in to ways you can enhance your C# development experience.
Future Articles
The topic of the next article is likely to be on the Entity Framework. You'll explore what it is and how it compares to LINQ. If you have something else in particular that you would like to see explained here, you could reach me at mark.strawmyer@crowehorwath.com.
About the Author
Mark Strawmyer is an executive with Crowe Horwath LLP in the Indianapolis office. He can be reached at mark.strawmyer@crowehorwath.com.

Read More... C# Tricks and tips