Saturday, May 21, 2011

Tips and Tricks about Google Talk

With Google Talk being all the craze right now, some people hating it, and others loving it, I figured that I would post a list of tips and tricks for those curious about the extra "features" Google implemented and has not said much about.

Registry Tweaks
You can edit most settings by opening regedit (start -> regedit),
and navigating to the key HKEY_CURRENT_USER\Software\Google\Google Talk.

The "Google/Google Talk" key has several sub-keys that hold different option values:

Accounts: This one has subkeys for each different account that has logged in on the client. These keys have different values that store the username, password and connection options.

Autoupdate: Stores the current version information. When the client checks for updates it compares Google's response with these values. If an update is needed, it will download and update the new version.

Options: This is the most interesting part, where most of the current hacks should be used (keep reading).

Process: Stores the process ID. Probably used by Google Talk to detect if it's already running or not.

1.) HKEY_CURRENT_USER\Software\Google\Google Talk\Options\show_pin
If 1, shows a "pin" next to the minimize button that keeps the windows on top of all the other open windows when clicked.

2.)HKEY_CURRENT_USER\Software\Google\Google Talk\Options\view_show_taskbutton

If 0, hides the taskbar button, and leaves the tray icon only, when the window is shown

3.)HKEY_CURRENT_USER\Software\Google\Google Talk\Options\away_inactive

If 1, status will be set as Away after the specified number of minutes.

4.)HKEY_CURRENT_USER\Software\Google\Google Talk\Options\away_screensaver

If 1, status will be set as Away after the specified number of minutes.

5.)HKEY_CURRENT_USER\Software\Google\Google Talk\Options\inactive_minutes
Number of inactive minutes to become away if auto-away is on.

Tips & Tricks
Wumpus Game : - First noted by a GoogleRumors commentor, if you add the buddy wumpus.game@gmail.com you can play the classic text-based game. Wumpus is an easter egg game that came with Google Talk (unfortunately, he didn't’t accept my invitation, so I can’t play).
Change the font size - While holding the control key, move the scroll wheel on your mouse either up or down. This trick works while being focused in either the read or write area.
Insert line breaks - If you want to have a message that spans multiple paragraphs, just hold shift and hit enter. You can add as many new lines as you want to create.
Bold Text - To write something bold, you can use an asterisk before and after the word, like *this* .
Italic Text - To use italics, use an underscore before an after the word, like _this_ .
Switch windows - Hitting tab will cycle through open windows. It will select minimized conversations, to expand them just hit enter. If you just want to cycle through IM's and don't care about the buddy list, control-tab will do that and will automatically expand a minimized conversation if you settle on one.
Invitation Tips - You don’t need to say Yes or No when someone wants to add you as a friend; you can simply ignore it, the request will go away. (On the other hand, someone with whom you chat often will automatically turn to be your friend, unless you disable this in the options).
Show Hyperlinks - You can show your homepage or blog URL simply by entering the it in your away message (at the top of the main window). It will automatically turn to a link visible to others.
Google Talk Game - “Google Talk” also was the name of a word game which uses Google.
A message can be 32767 characters long.
How To
Conference Calls :
What you need to do to have conference calls: Open up a copy of Google Talk on all computers with which you wish to conference. After one copy is opened make a new shortcut for Google Talk but at the end of it add /nomutex. If you installed it to the default folder then your shortcut should read "C:\Program Files\Google\Google Talk\googletalk.exe" /nomutex. Open 2nd instances of the software on every user's computer. After this start a chain: User 1 should connect on one instance to user 2. User 2 will connect on his second instance to user 3. User 3 will connect using his second instance back to user 1. With this chain everyone is connected to everyone.

Nickname & Status Message :
You can't change your nickname in a way that other people will see it change. Every nickname in the Google Talk contactlist is the part that is before @gmail.com (only the alphabetical characters are used) or the name you chosen for your GMail account. To change the nickname need to go to your Gmail account and change the name there. Choose Settings, Accounts, and then Edit info. Click on the second radio button, and enter your custom name. As a result all of your emails will have that nick as well, there is no way to seperate the two. You can add a website in your custom message, it will be clickable when someone opens a conversation window with you.

Contacts :
You don't need to say Yes or No when someone wants to add you as a friend; you can simply ignore it, the request will go away. (On the other hand, someone with whom you chat often will automatically turn to be your friend, unless you disable this).
The Gmail account 'user@gmail.com' can't be invited as your friend.

Sound & Video :
It's possible to broadcast music, MP3, etc.. through Google Talk.
Unplug your microphone. Double click on the speaker icon in the lower right corner. This will open up "Volume Control". Select "Options" and then "Properties". Then check the button next to "Recording" then click OK. You may also have to change your setting under Mixer Device. Now the Recording Control screen should be up. On my computer I selected "Wave Out Mix". Click on the green phone in Google Talk and call your friend.

Keyboard Shortcuts
Ctrl + E - It centralizes the selected text, or the current line.
Ctrl + R - It justifies to the right the selected text, or the current line.
Ctrl + L - It justifies to the left the selected text, or the current line.
Ctrl + I - The same thing does that Tab.
Tab - It is giving the area to each of the windows opened by Google Talk.
Ctrl + Tab - The same thing does that Shift + Tab .
Shift + Tab - The same thing does that Tab but in reverse.
Ctrl + Shift + L -Switch between points, numbers, letters, capital letters, roman numbers and capital roman numbers
Ctrl + 1 (KeyPad) - It does a simple space between the lines.
Ctrl + 2 (KeyPad) - It does a double space between the lines.
Ctrl + 5 (KeyPad) - A space does 1.5 between the lines.
Ctrl + 1 (NumPad) - It goes at the end of the last line.
Ctrl + 7 (NumPad) - It goes at the begin of the last line.
Ctrl + F4 - It closes the current window.
Alt + F4 - It closes the current window.
Alt + Esc - It Minimize all the windows.
Windows + ESC - Open Google Talk (if it's minimized, or in the tray)
F9 - Open Gmail to send an email to the current contact.
F11 - It initiates a telephonic call with your friend.
F12 - It cancels a telephonic call.
Esc - It closes the current window.
[HOWTO] Use multiple identities on Google Talk
Want to run Google Talk with multiple Gmail identities? If you have several Google Gmail accounts you also may want to run multiple instances of Google Talk This is especially important for families that share a single PC. Nothing worse than a family member signing you out so they can sign in under their own account!

Basically, to have "Google Polygamy" you need to run Google Talk with the following switch: /nomutex

Step 1: Right-click on the desktop
Step 2: Select New
Step 3: Select Shortcut
Step 4: Paste this into the text box:

"c:\program files\google\google talk\googletalk.exe" /nomutex

Step 5: Click Next and choose a shortcut name such as Google Talk1, Google Talk2, or something related to your Gmail account for easy remembering which account is which.
Step 6: Click OK a few times.
[HOWTO] Use Google Talk via a Web Browser
You want to use Google Talk anywhere ? Follow these guidelines :)

Step 1: Opens your favorite web browser at the following address :

http://www.webjabber.net:8080/jim/
Step 2: Follow the instructions of the Page.

Step 3: You can talk with your friends

Google's Secret Command-Line Parameters
There are a few secret parameters you can add to Google Talk and make it function differently.

The most important, I think, is /nomutex, which allows you to run more than one instance of GT. Here are the others:

/nomutex: allows you to open more than one instance of Google Talk
/autostart: when Google Talk is run with this parameter, it will check the registry settings to see if it needs to be started or not. If the "Start automatically with Windows" option is unchecked, it won't start.
/forcestart: same as /autostart, but forces it to start no matter what option was set.
/S upgrade: Used when upgrading Google Talk
/register: registers Google Talk in the registry, includig the GMail Compose method.
/checkupdate: check for newer versions
/plaintextauth: uses plain authentication mechanism instead then Google's GAIA mechanism. Used for testing the plain method on Google's servers.
/nogaiaauth: disables GAIA authentication method. The same as above.
/factoryreset: set settings back to default.
/gaiaserver servername.com: uses a different GAIA server to connect to Google Talk. Used for debug purposes only, there are no other known GAIA servers.
/mailto email@host.com: send an email with Gmail
/diag: start Google Talk in diagnostic mode
/log: probably has something to do with the diagnostic logging
/unregister: ?
/embedding: ?
To add these, open up your GT shortcut, and where it says "Target:" add one or more of these inside the quotations, but after the .exe part.

Emotions :

All these emotions appears in color in a conversation : (but having them in an image would be better, like iChat or MSN)

:-|
:-O
:-x
:-P
:-D
;-)
:-(
:-)
B-)
:'(
:|
:O
:x
:P
:D
:)
:(
:)

Tips and Tricks about Google

I have been quite fascinated by Google ever since they started out as a search engine. Over the time Google has become an indispensable tool for any serious geek. I will describe a few techniques that I use. They have been collected from various help pages, chat rooms and books. If you find any error please point it out.

1.) Common queries:
So how will you effectively use Google. Take this example. A friend of mine was asking me over yahoo messenger what is a blog. I told him to search on Google and find out. He tried this.
blog
Alas the answer was there but lost in thousands of links. He alerted me that he can't find an answer. I told " Ok , Let me see What is wrong? ". I tried this

What is blog
The answer was right there.

While formulating search queries you must be specific as far as possible. A query like Linux vpn howto can yield a different result than vpn howto. Google seems to be intelligent enough to understand some human thought chain. So while making queries be a bit descriptive and formulate a properly worded query. Google ignores some of the common words such as 'the' 'and' 'a' etc while performing a search.

2.) How to formulate a good search string :
Google uses AND logic for the queries by default. If you search linux vpn howto google searches for pages containing linux AND vpn AND howto. You can put OR logic in the search box like this

linux OR vpn OR howto

You can exclude some terms using "-"

linux vpn -installation

Try ( linux vpn - installation ) and see how it is different from the above query. You can group a set of terms by enclosing them in brackets. It is also possible to combine AND and OR operators.

It may be noted that Google is not case sensitive regarding search strings. Linux, LINUX and linux produces the same results. However the operators such as AND and OR are case sensitive.

3.) Searching for a file :

Suppose you want to search for pdf documents only. You can do this by attaching a filetype modifier to your query. A typical query can look like this
vpn filetype:pdf
Google can recognize most common filetyes.

4.) Searching only at a site :

This is similar to file type modifier. Try this VPN site:ibm.com
Then try vpn site:edu filetype:pdf You can get some interesting result by trying this query
linux site:microsoft.com
5.) Searching in URLs and Page titles :
You can search in urls using inurl modifier. Try inurl:smb.conf

Similarly you can use intitle modifier.

6.) Searching in Google cache :
If you are looking for some old web site you can directly search in Google cache.
Try cache:slashdot.org and see the cached pages.

7.) Looking for definitions :
This can be handy if your school going kid pesters you for his home work.
Try

define:watt
It bring out definitions from around the web.

8.) Looking at Google advanced search :
I think it is one link that most people try to ignore. It is designed for commoners. Almost all the options I mentioned above are available through advanced search.

The preferences page is also worth a visit. It uses cookies to set preferences such as number of search results to be displayed, language preferences etc.

9.) Finding the price of some geek gadget :
Google has a companion site called froogle.com. Its interface is exactly similar. But it returns prices across various stores in the US. This feature can be very useful if you plan to buy some strange hardware. Let us hope that froogle.co.in will appear soon.
10.) Google Calculator :
In the google search :
Type in an equation: (100+4567*10-200=)
What is the square root of 267? (sqrt(267))

11.) Google labs :
Google is very innovative and always tries to introduce new features. You can see some of the upcoming features at labs.google.com . Also Google conducts a puzzle champion ships annually.

12.) Google Sets :
Google sets is an interesting feature currently available at http://labs.google.com/sets.

Have a look at the page. You will see a number of text boxes. Enter some words which belongs to a set of items and search. Google will complete the set.

I typed in the names of following linux distributions " Mandrake" "Suse" " "debian" and hit larger set button. Google provided a huge list of linux distributions.

Basic of C#

C# is a language with the features of C++, programming style like Java and rapid application model of BASIC. If you already know the C++ language, it will take you less than an hour to quickly go through the syntax of C#. Familiarity with Java will be a plus, as Java program structure, the concept of packages and garbage collection will definitely help you learn C# more quickly. So while discussing C# language constructs, I will assume, you know C++.

This article discusses the C# language constructs and features using code examples, in a brief and comprehensive way, so that you just by having a glance at the code, can understand the concepts.

Note: This article is not for C# gurus. There must be some other beginner's articles on C#, but this is yet another one.

Following topics of C# language are discussed:

* Program structure
* Namespaces
* Data types
* Variables
* Operators and expressions
* Enumerations
* Statements
* Classes and structs
* Modifiers
* Properties
* Interfaces
* Function parameters
* Arrays
* Indexers
* Boxing and unboxing
* Delegates
* Inheritance and polymorphism

Following are not discussed:

* Things which are common in C++ and C#.
* Concepts like garbage collection, threading, file processing etc.
* Data type conversions
* Exception handling
* .NET library

Program structure

Like C++, C# is case-sensitive. Semi colon (;) is the statement separator. Unlike C++, there are no separate declaration (header) and implementation (CPP) files in C#. All code (class declaration and implementation) is placed in one file with extension cs.

Have a look at this Hello world program in C#.

using System;

namespace MyNameSpace

{
class HelloWorld

{
static void Main(string[] args)
{
Console.WriteLine ("Hello World");
}
}
}

Everything in C# is packed into a class and classes in C# are packed into namespaces (just like files in a folder). Like C++, a main method is the entry point of your program. C++'s main function is called main whereas C#'s main function starts with capital M and is named as Main.

No need to put a semi colon after a class block or struct definition. It was in C++, C# doesn't require that.
Namespace

Every class is packaged into a namespace. Namespaces are exactly the same concept as in C++, but in C# we use namespaces more frequently than in C++. You can access a class in a namespace using dot (.) qualifier. MyNameSpace is the namespace in hello world program above.

Now consider you want to access the HelloWorld class from some other class in some other namespace.

using System;
namespace AnotherNameSpace
{
class AnotherClass
{
public void Func()
{
Console.WriteLine ("Hello World");
}
}
}

Now from your HelloWorld class you can access it as:

using System;
using AnotherNameSpace; // you will add this using statement

namespace MyNameSpace
{
class HelloWorld
{
static void Main(string[] args)
{
AnotherClass obj = new AnotherClass();
obj.Func();
}
}
}

In .NET library, System is the top level namespace in which other namespaces exist. By default there exists a global namespace, so a class defined outside a namespace goes directly into this global namespace and hence you can access this class without any qualifier.

You can also define nested namespaces.
Using

The #include directive is replaced with using keyword, which is followed by a namespace name. Just as using System as above. System is the base level namespace in which all other namespaces and classes are packed. The base class for all objects is Object in the System namespace.
Variables

Variables in C# are almost the same as in C++ except for these differences:

1. Variables in C# (unlike C++), always need to be initialized before you access them, otherwise you will get compile time error. Hence, it's impossible to access an un-initialized variable.
2. You can't access a dangling pointer in C#.
3. An expression that indexes an array beyond its bounds is also not accessible.
4. There are no global variables or functions in C# and the behavior of globals is achieved through static functions and static variables.

Data types

All types of C# are derived from a base class object. There are two types of data types:

1. Basic/ built-in types
2. User-defined types

Following is a table which lists built-in C# types:

Type Bytes Description
byte 1 unsigned byte
sbyte 1 signed byte
short 2 signed short
ushort 2 unsigned short
int 4 signed integer
uint 4 unsigned integer
long 8 signed long
ulong 8 unsigned long
float 4 floating point number
double 8 double precision number
decimal 8 fixed precision number
string Unicode string
char Unicode char
bool true, false boolean

Note: Type range in C# and C++ are different, example, long in C++ is 4 bytes, and in C# it is 8 bytes. Also the bool and string types are different than those in C++. bool accepts only true and false and not any integer.

User defined types includes:

1. Classes
2. Structs
3. Interfaces

Memory allocation of the data types divides them into two types:

1. Value types
2. Reference types

Value types

Values types are those data types which are allocated in stack. They include:

* All basic or built-in types except strings
* Structs
* Enum types

Reference types

Reference types are allocated on heap and are garbage collected when they are no longer being used. They are created using new operator, and there is no delete operator for these types unlike C++ where user has to explicitly delete the types created using delete operator. In C#, they are automatically collected by garbage collector.

Reference types include:

* Classes
* Interfaces
* Collection types like Arrays
* String

Enumeration

Enumerations in C# are exactly like C++. Defined through a keyword enum.

Example:

enum Weekdays
{
Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday
}

Classes and structs

Classes and structs are same as in C++, except the difference of their memory allocation. Objects of classes are allocated in heap, and are created using new, where as structs are allocated in stack. Structs in C# are very light and fast data types. For heavy data types, you should create classes.

Examples:

struct Date
{
int day;
int month;
int year;
}

class Date
{
int day;
int month;
int year;
string weekday;
string monthName;
public int GetDay()
{
return day;
}
public int GetMonth()
{
return month;
}
public int GetYear()
{
return year;
}
public void SetDay(int Day)
{
day = Day ;
}
public void SetMonth(int Month)
{
month = Month;
}
public void SetYear(int Year)
{
year = Year;
}
public bool IsLeapYear()
{
return (year/4 == 0);
}
public void SetDate (int day, int month, int year)
{
}
...
}

Properties

If you are familiar with the object oriented way of C++, you must have an idea of properties. Properties in above example of Date class are day, month and year for which in C++, you write Get and Set methods. C# provides a more convenient, simple and straight forward way of accessing properties.

So above class can be written as:

using System;
class Date
{
public int Day{
get {
return day;
}
set {
day = value;
}
}
int day;

public int Month{
get {
return month;
}
set {
month = value;
}
}
int month;

public int Year{
get {
return year;
}
set {
year = value;
}
}
int year;

public bool IsLeapYear(int year)
{
return year%4== 0 ? true: false;
}
public void SetDate (int day, int month, int year)
{
this.day = day;
this.month = month;
this.year = year;
}
}

Here is the way you will get and set these properties:
class User
{
public static void Main()
{
Date date = new Date();
date.Day = 27;
date.Month = 6;
date.Year = 2003;
Console.WriteLine
("Date: {0}/{1}/{2}", date.Day, date.Month, date.Year);
}
}

Modifiers

You must be aware of public, private and protected modifiers that are commonly used in C++. I will here discuss some new modifiers introduced by C#.
readonly

readonly modifier is used only for the class data members. As the name indicates, the readonly data members can only be read, once they are written either by directly initializing them or assigning values to them in constructor. The difference between the readonly and const data members is that const requires you to initialize with the declaration, that is directly. See example code:

class MyClass
{
const int constInt = 100; //directly

readonly int myInt = 5; //directly

readonly int myInt2;

public MyClass()
{
myInt2 = 8; //Indirectly

}
public Func()
{
myInt = 7; //Illegal

Console.WriteLine(myInt2.ToString());
}

}

sealed

sealed modifier with a class don't let you derive any class from it. So you use this sealed keyword for the classes which you don't want to be inherited from.

sealed class CanNotbeTheParent
{
int a = 5;
}

unsafe

You can define an unsafe context in C# using unsafe modifier. In unsafe context, you can write an unsafe code, example: C++ pointers etc. See the following code:

public unsafe MyFunction( int * pInt, double* pDouble)
{
int* pAnotherInt = new int;
*pAnotherInt = 10;
pInt = pAnotherInt;
...
*pDouble = 8.9;
}

Interfaces

If you have an idea of COM, you will immediately know what I am talking about. An interface is the abstract base class containing only the function signatures whose implementation is provided by the child class. In C#, you define such classes as interfaces using the interface keyword. .NET is based on such interfaces. In C#, where you can't use multiple class inheritance, which was previously allowed in C++, the essence of multiple inheritance is achieved through interfaces. That's your child class may implement multiple interfaces.

using System;
interface myDrawing
{
int originx
{
get;
set;
}
int originy
{
get;
set;
}
void Draw(object shape);
}

class Shape: myDrawing
{
int OriX;
int OriY;

public int originx
{
get{
return OriX;
}
set{
OriX = value;
}
}
public int originy
{
get{
return OriY;
}
set{
OriY = value;
}
}
public void Draw(object shape)
{
... // do something

}

// class's own method

public void MoveShape(int newX, int newY)
{
.....
}

}

Arrays

Arrays in C# are much better than C++. Arrays are allocated in heap and thus are reference types. You can't access an out of bound element in an array. So C# prevents you from that type of bugs. Also some helper functions to iterate array elements are provided. foreach is the statement for such iteration. The difference between the syntax of C++ and C# array is:

* The square brackets are placed after the type and not after the variable name
* You create element locations using new operator.

C# supports single dimensional, multi dimensional, and jagged arrays (array of array).

Examples:

int[] array = new int[10]; // single-dimensional array of int

for (int i = 0; i < array.Length; i++)
array[i] = i;

int[,] array2 = new int[5,10]; // 2-dimensional array of int

array2[1,2] = 5;

int[,,] array3 = new int[5,10,5]; // 3-dimensional array of int

array3[0,2,4] = 9;

int[][] arrayOfarray = new int[2]; // Jagged array - array of array of int

arrayOfarray[0] = new int[4];
arrayOfarray[0] = new int[] {1,2,15};

Indexers

Indexer is used to write a method to access an element from a collection, by straight way of using [], like an array. All you need is to specify the index to access an instance or element. Syntax of Indexer is same as that of class properties, except they take the input parameter, that is the index of the element.

Example:

Note: CollectionBase is the library class used for making collections. List is the protected member of CollectionBase which stores the collection list.

class Shapes: CollectionBase
{
public void add(Shape shp)
{
List.Add(shp);
}

//indexer

public Shape this[int index]
{
get {
return (Shape) List[index];
}
set {
List[index] = value ;
}
}
}

Boxing/Unboxing

The idea of boxing is new in C#. As mentioned above, all data types, built-in or user defined, are derived from a base class object in the System namespace. So the packing of basic or primitive type into an object is called boxing, whereas the reverse of this known as unboxing.

Example:

class Test
{
static void Main()
{
int myInt = 12;
object obj = myInt ; // boxing

int myInt2 = (int) obj; // unboxing

}
}

Example shows both boxing and unboxing. An int value can be converted to object and back again to int. When a variable of a value type needs to be converted to a reference type, an object box is allocated to hold the value, and the value is copied into the box. Unboxing is just the opposite. When an object box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location.
Function parameters

Parameters in C# are of three types:

1. By-Value/In parameters
2. By-Reference/In-Out parameters
3. Out parameters

If you have an idea of COM interface and it's parameters types, you will easily understand the C# parameter types.
By-Value/In parameters

The concept of value parameters is same as in C++. The value of the passed value is copied into a location and is passed to the function.

Example:

SetDay(5);
...
void SetDay(int day)
{
....
}

By-Reference/In-Out parameters

The reference parameters in C++ are passed either through pointers or reference operator &. In C# reference parameters are less error prone. Reference parameters are also called In-Out parameters because you pass a reference address of the location, so you pass an input value and get an output value from that function.

You can not pass an un-initialized reference parameter into a function. C# uses a keyword ref for the reference parameters. You also have to use keyword ref with an argument while passing it to a function demanding reference parameter.

Example:

int a= 5;
FunctionA(ref a); // use ref with argument or you will get compiler error

Console.WriteLine(a); // prints 20


void FunctionA(ref int Val)
{
int x= Val;
Val = x* 4;
}

Out parameter

Out parameter is the parameter which only returns value from the function. The input value is not required. C# uses a keyword out for the out parameters

Example:

int Val;
GetNodeValue(Val);

bool GetNodeValue(out int Val)
{
Val = value;
return true;
}

Variable number of parameters and arrays

Arrays in C# are passed through a keyword params. An array type parameter should always be the right most argument of the function. Only one parameter can be of array type. You can pass any number of elements as an argument of type of that array. You can better understand it from example below:

Note: This is the only way C# provides for optional or variable number of parameters, that is using array.

Example:

void Func(params int[] array)
{
Console.WriteLine("number of elements {0}", array.Length);
}


Func(); // prints 0

Func(5); // prints 1

Func(7,9); // prints 2

Func(new int[] {3,8,10}); // prints 3

int[] array = new int[8] {1,3,4,5,5,6,7,5};
Func(array); // prints 8

Operators and expressions

Operators are exactly the same as of C++ and thus the expression also. However some new and useful operators are also added. Some of them are discussed here.
is operator

is operator is used to check whether the operand types are equal or convert-able. The is operator is particularly useful in the polymorphism scenarios. is operator takes two operands and the result is a boolean. See the example:

void function(object param)
{
if(param is ClassA)
//do something

else if(param is MyStruct)
//do something

}
}

as operator

as operator checks if the type of the operands are convert-able or equal (as is done by is operator) and if it is, the result is a converted or boxed object (if the operand can be boxed into the target type, see boxing/unboxing). If the objects are not convert-able or box-able, the return is a null. Have a look at the example below to better understand the concept.

Shape shp = new Shape();
Vehicle veh = shp as Vehicle; // result is null, types are not convertable


Circle cir = new Circle();
Shape shp = cir;
Circle cir2 = shp as Circle; //will be converted


object[] objects = new object[2];
objects[0] = "Aisha";
object[1] = new Shape();

string str;
for(int i=0; i&< objects.Length; i++)
{
str = objects[i] as string;
if(str == null)
Console.WriteLine("can not be converted");
else
Console.WriteLine("{0}",str);
}

Output:
Aisha
can not be converted

Statements

Statements in C# are just like in C++ except some additions of new statements and modifications in some statements.

Followings are new statements:
foreach

For iteration of collections like arrays etc.

Example:

foreach (string s in array)
Console.WriteLine(s);

lock

Used in threads for locking a block of code making it a critical section.
checked/unchecked

The statements are for overflow checking in numeric operations.

Example:

int x = Int32.MaxValue; x++; // Overflow checked

{
x++; // Exception

}
unchecked
{
x++; // Overflow}

}
Following statements are modified:

Switch

Switch statement is modified in C#.

1. Now after executing a case statement, program flow can not jump to next case which was previously allowed in C++.

Example:
int var = 100;
switch (var)
{
case 100: Console.WriteLine(""); // No break here

case 200: Console.WriteLine(""); break;
}

Output in C++:



In C# you get compile time error:

error CS0163: Control cannot fall through
from one case label ('case 100:') to another

2. However you can do this similar to how you do it in C++:

switch (var)
{
case 100:
case 200: Console.WriteLine("100 or 200"); break;
}

3. You can also use constant variables for case values:

Example:

const string WeekEnd = "Sunday";
const string WeekDay1 = "Monday";

....

string WeekDay = Console.ReadLine();
switch (WeekDay )
{
case WeekEnd: Console.WriteLine("It's weekend!!"); break;
case WeekDay1: Console.WriteLine("It's Monday"); break;

}

Delegates

Delegates let us store function references into a variable. In C++, this is like using and storing function pointer for which we usually use typedef.

Delegates are declared using a keyword delegate. Have a look at this example, and you will understand what delegates are:

Example:

delegate int Operation(int val1, int val2);
public int Add(int val1, int val2)
{
return val1 + val2;
}
public int Subtract (int val1, int val2)
{
return val1- val2;
}

public void Perform()
{
Operation Oper;
Console.WriteLine("Enter + or - ");
string optor = Console.ReadLine();
Console.WriteLine("Enter 2 operands");

string opnd1 = Console.ReadLine();
string opnd2 = Console.ReadLine();

int val1 = Convert.ToInt32 (opnd1);
int val2 = Convert.ToInt32 (opnd2);

if (optor == "+")
Oper = new Operation(Add);
else
Oper = new Operation(Subtract);

Console.WriteLine(" Result = {0}", Oper(val1, val2));
}

Inheritance and polymorphism

Only single inheritance is allowed in C#. Multiple inheritance can be achieved using interfaces.

Example:

class Parent{
}

class Child : Parent

Virtual functions

Virtual functions to implement the concept of polymorphism are same in C#, except you use the override keyword with the virtual function implementation in the child class. The parent class uses the same virtual keyword. Every class which overrides the virtual method will use override keyword.

class Shape
{
public virtual void Draw()
{
Console.WriteLine("Shape.Draw") ;
}
}

class Rectangle : Shape

{
public override void Draw()
{
Console.WriteLine("Rectangle.Draw");
}
}

class Square : Rectangle
{
public override void Draw()
{
Console.WriteLine("Square.Draw");
}
}
class MainClass
{
static void Main(string[] args)
{
Shape[] shp = new Shape[3];
Rectangle rect = new Rectangle();

shp[0] = new Shape();
shp[1] = rect;
shp[2] = new Square();

shp[0].Draw();
shp[1].Draw();
shp[2].Draw();
}
}
Output:
Shape.Draw
Rectangle.Draw
Square.Draw

Hiding parent functions using "new"

You can define in a child class a new version of a function, hiding the one which is in base class. A keyword new is used to define a new version. Consider the example below, which is a modified version of above example and note the output this time, when I replace the keyword override with a keyword new in Rectangle class.

class Shape
{
public virtual void Draw()
{
Console.WriteLine("Shape.Draw") ;
}
}

class Rectangle : Shape
{
public new void Draw()
{
Console.WriteLine("Rectangle.Draw");
}
}
class Square : Rectangle
{
//wouldn't let u override it here

public new void Draw()
{
Console.WriteLine("Square.Draw");
}
}
class MainClass
{
static void Main(string[] args)
{
Console.WriteLine("Using Polymorphism:");
Shape[] shp = new Shape[3];
Rectangle rect = new Rectangle();

shp[0] = new Shape();
shp[1] = rect;
shp[2] = new Square();

shp[0].Draw();
shp[1].Draw();
shp[2].Draw();

Console.WriteLine("Using without Polymorphism:");
rect.Draw();
Square sqr = new Square();
sqr.Draw();
}
}

Output:
Using Polymorphism
Shape.Draw
Shape.Draw
Shape.Draw
Using without Polymorphism:
Rectangle.Draw
Square.Draw

See how the polymorphism doesn't take the Rectangle class's Draw method as a polymorphic form of the Shape's Draw method, instead it considers it a different method. So in order to avoid the naming conflict between parent and child, we have used new modifier.

Note: you can not use in the same class the two versions of a method, one with new modifier and other with override or virtual. Like in above example, I can not add another method named Draw in Rectangle class which is a virtual or override method. Also in the Square class, I can't override the virtual Draw method of Shape class.
Calling base class members

If the child class has the data members with same name as that of base class, in order to avoid naming conflicts, base class data members and functions are accessed using a keyword base. See in examples how the base class constructors are called and how the data members are used.

public Child(int val) :base(val)
{
myVar = 5;
base.myVar;
}

OR

public Child(int val)
{
base(val);
myVar = 5 ;
base.myVar;
}

Future additions

This article is just a quick overview of the C# language so that you can just become familiar with the language features. Although I have tried to discuss almost all the major concepts in C# in a brief and comprehensive way with code examples, yet I think there is lot much to be added and discussed.

In future, I would like to add more commands and concepts not yet discussed, including events etc. I would also like to write for beginners, about Windows programming using C#.
References:

* Our most commonly known MSDN
* Inside C# by Tom Archer
* A Programmer's Introduction to C# by Eric Gunnerson
* Beginning C# by Karli Watson
* Programming C# (O'Reilly)