Monday, August 31, 2009

Helpful Keywords

1. __arglist

Lets start with __arglist. __arglist is used to send parameters to a method. Generally we used to send parameters to a function by having a list of arguments specified in the method head. If we want to pass a new set of arguments we need to have Method Overloading. Even when we want to send any number of arguments we might use param array.

Now why should we use __arglist. In case of each of these methods, the problems are :

1. If we use Method Overloading, we might have to add new methods whenever a new set of argument list is thought to be sent.
2. If we use param array we need to have same type of arguments or need to have param array of objects.


__arglist releaves each of those. It can send any no of argument to a function. It might be of any type and we can parse each argument easily using simple steps.

Lets have a look at the Code :


public int paramLength(__arglist)
{
ArgIterator iterator = new ArgIterator(__arglist);
return iterator.GetRemainingCount();
}


Now if I call the function using this statement

int x = this.paramLength(__arglist(49,34,54,6,"Manimoy")); // returns 5


5 will be returned to the variable x. It is because we send 5 arguments to the method. We can access each methods using :


TypedReference tf = iterator.GetNextArg();
TypedReference.ToObject(tf)

On each call to GetNextArg, the GetRemainingCount will decrease by one until it wipes out each objects set to the iterator.

2. __refvalue


Another interesting keyword you can use instead is __refvalue. It is used to fetch the value from a reference object. You can use this to get the actual object from TypedReference object.

It takes 2 arguments, first one is the object of TypedReference and the Type in which to cast. Take a look on the line below :


int tfValue = __refvalue(tf, int);

On the execution of the line tfValue will be assigned to the value of the integer where tf is pointing.

3. __makeref


Another undocumented keyword is __makeref which will give the TypedReference object from the object itself. This is just the reverse to __refvalue. Take a look at the code below :


string name = "Ayan";
TypedReference tf = __makeref(name);
4. __reftype

__reftype is used to get Type object from a TypedReference. Have a look at the code below to understand the use :


Type t = __reftype(tf);
if(t.ToString().equals("System.String"))
string str = __refvalue(t,string);

Note : Though I found these keywords in all the versions of C#, yet I dont use it in production environment. There is no sureity of these keywords to be there in future version of C#, so use it in your own risk.


Documented Yet Uncommon


In this section, I am going to discuss some of the uncommon documented keywords which is not needed very often while we do programs. Let us discuss the most common one here in this section.
1. Yield

Yield is a keyword introduced in .NET 2.0, is used to yield a list of return statements in the form of IEnumerable. The block which yields IEnumerable is commonly called as iterator block. In the code below, I have created a list of few names and returned the list of all of them which has lenght less than 5 until it reaches yield break statement for a length <12


List< string < lst = new List< string <();
lst.Add("Abhishek");
lst.Add("Abhijit");
lst.Add("Manimoy");
lst.Add("Raj");
lst.Add("Ayan");
lst.Add("MacMillanRojer");
lst.Add("Rizzuto");
foreach (string x in lst)
{
if (x.Length < 12) // Breaks on MacMillanRojer
yield break;
else if (x.Length < 5) // Only returns those which are having length <5
yield return x;
else continue;
}


Actually the yield return x will evaluate each elements and creates the enumerable of all the elements that satisfies the condition(length <5).
The break statement will terminate the loop and return the existing Enumerable created.

2. Fixed

Another uncommon keyword is Fixed which can only be used in Unsafe C# code blocks. Fixed statement sets the pointer to be in a fixed memory address so that, it will not be moved to anywhere even if Garbage Collection Thread is invoked. Let us have a look at the code below:


int[] a = new int[] { 1, 2, 3 };
fixed (int* pt = a)
{
int* c = pt;
MessageBox.Show("Value : " + *c);
// This will fix the variable totally so that it will
// not be moved when Garbage collector is invoked.
}

Here, the Pointer c is be assigned the same location as pt.

Fixed often comes at a cost. It is actually hampers the normal process of Garbage collection. Thus if is good to avoid fixed statement if not actually needed.

3 Checked / Unchecked


Another keyword called checked which is used to control arithmetic overflow context. Checked keyword throws StackOverflowException when an arithmetic operation overflows the necessary size.

Take a look at the code :


int x = int.MaxValue;
int y = int.MaxValue;
int z = checked(x + y);

The above statement throws StackOverflowException when x+y is invoked. The checked is used to check the overflow in arithmetic calculations and throw exception accordingly. z is assinged to 0 when StackOverflowException occurs.

We might use unchecked keyword when we dont need to throw exception.


int x = int.MaxValue;
int y = int.MaxValue;
int z = unchecked(x + y);

Through execution of above code the value of z will be assinged to -2.
4. Volatile


Volatile keyword is used to define a variable which is to be modified across multiple threads without invoking lock statements. Volatile variables are not subject to compiler optimization and thus we will get the most updated value of the variable all the time. See the example below :

public volatile int i;
Thread th = new Thread(new ThreadStart(VolatileInvoke));
th.Start();
Thread.Sleep(5000); //Holds current Thread for 5 seconds.
MessageBox.Show("Value of i : " + i);
th.Abort();

private void VolatileInvoke()
{
while (true)
{
i++;
}
}

The thread is started and will increment the volatile integer value by 1 until it is aborted by the main thread.

Note : Volatile types dont have Thread optimization.
5. StackAlloc


It is also used with unsafe C# code which allocates memory dynamically from stack. stackalloc is used to aquire memory quickly when it is very essential to get a large amount of memory. We can declare an array like this :


int* array = stackalloc new int[1000]
The memory is available as soon as the statement is invoked.

6. Global ::


It is very handy when local namespace hides global namespace. Suppose we have created a class named System in our project. C# allowes to do that. But the problem is that whenever I want to call System that is defined in the global space, we unable to do that without using global::. Let us see the example below :


internal class System
{
internal class Array :IEnumerable
{
public int Length
{
get{return 1000}
}
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
Debug.Write("This is Dummy Array");
this.GetEnumerator();
}

#endregion
}
}

Now if you want to call System.Array it will call the one defined locally. To call global System we need to use global::System

It is always better to use global:: when you are sure of calling the global namespace. This ensures your code to work even in this sort of weird situations.

7. Namespace Alias


Namespace alias are used when you want to shorten a long namespace. To do that :


using Abhishek = System.Drawing;
public class X
{
public X()
{
Abhishek.Graphics g = this.CreateGraphics();
}
}

Here in the header we made an alias Abhishek of System.Drawing. Thus within the code if we refer to Abhishek, it will be same as referring to System.Drawing.

8. extern alias

Most of us while working with C# have used external control sets. There may come a situation when we want to add 2 versions of dlls in the same application with same Fully Qualified Namespaces. In such cases we need extern alias feature to refer to two different assemblies.
For example:

Suppose we add an assembly x10.dll (V1) which have a class called Y.
We add x20.dll(V2) where we may want to use Class Y.

First of all, to reference the fully qualified assembly we need to declare an alias in command line. /r:XV1=X10.dll

/r:XV2=X20.dll

Now to reference that we use


extern alias XV1;
extern alias XV2;
9. ?? (Null coalescing operator)

Null coalescing operator is used to work with null values. It is introduced in 2.0. See the following :


MyClass x = null;
x = x ?? new MyClass();

?? means if x has null value it will call new MyClass() otherwise it will assing the existing x.

10. @variables


Generally C# doesnt allow to create variables in the same name as keywords. But there is a way out to this. We can define variable with same name as keywords using @.
Suppose we define

int @int = 10;

That means a variable with name int is declared and assigned a value 10 in it.

11. Readonly


readonly is a keyword present in C# which is used to create variables that will not change throughout the program. The variable declared as readonly will be assigned its value only once and it will remain the same value throughout the execution of the object.

To declare a variable as readonly :

public readonly int readonlyvariable = 20;

This will instruct the program to make the variable 20 and any further re-assign to the variable is not permitted.

12 Difference between Const & readonly ?

readonly is almost similar to const keyword. The only difference is that const variables are defined in compile time, while readonly variables are defined at runtime during initialisation. You can assing readonly variables from within constructors, so based on the constructor call you may assign readonly values differently.


public readonly int readsecond;
public Documented()
{
readsecond = DateTime.Now.Second;
}
Here the readsecond will assign values differently based on the object initialisation, which is impossible in case of const.

13 Default

Sometimes default keywords comes very handy when working with generic objects. It returns the default value when the object is not initialised. For example, we all know integers are initialised to 0 if not given any value. Characters are Empty when not given any value, objects are null when not assigned any value.

These values are assigned based on default keyword.
Thus if we write :

int x = default(int);//will be assigned to 0
will be same as
int x;

In case of Generic object when the type is undefined, we can use default to assign specific value to the object. Let us look at the sample :


public T GetDefault< T <()
{
return default(T);
}
The function returns default value for each individual types sent. Thus


int defx = this.GetDefault< int <(); //will assign 0
char defy = this.GetDefault< char <(); // will assign empty
object defz = this.GetDefault< object <(); // will assign null
Thus we can use default keyword to get the default assignments to the object very easily.

14. Nullable Types

Nullable types of C# can handle nulls even being premitive data types. Each nullable types are derived from System.Nullable. We can define nullables like this :

int? nullableint = null;

Thus nullableint will be assigned to null.

If you access nullable variables, you will get 2 properties.

HasValue which returns false if null is assigned to the variable, and Value which returns the actual value of the variable. You can also use GetValueOrDefault function of each nullable type object to get the default value when null is assigned to the variable.
Read More

Fill dropdownlist from enum

as we all know that enum is very useful and sometimes we need to show values of enum on dropdownlist. by following way we can show data of enum in dropdownlist
enum CustomColors
{
BLACK = -1,
RED = 7,
GREEN = 14,
UNKNOWN = -13
}

protected void BtnFillddl_Click(object sender, EventArgs e)
{
EnumToListBox(typeof(DayOfWeek), DropDownList1);

EnumToListBox(typeof(CustomColors), ListBox1);
}
static public void EnumToListBox(Type EnumType, ListControl TheListBox)
{
Array Values = System.Enum.GetValues(EnumType);

foreach (int Value in Values)
{
string Display = Enum.GetName(EnumType, Value);
ListItem Item = new ListItem(Display, Value.ToString());
TheListBox.Items.Add(Item);
}
}
Read More

Sunday, August 30, 2009

Master the Command Window

Visual Studio has hundreds of menus, windows, and dialog boxes. This you are probably aware of; what you
may not be aware of is that you can avoid using all of these and use the command line inside the command
window instead. This hack looks at some of the different commands available to you, how to use existing aliases,
and how to create and manage your own aliases.

So why would you want to use a command window when you could just use some part of the IDE? Using the
command window is sometimes faster than using the IDE, and when you are writing code with both of your
hands on the keyboard, it is often easier and faster to type a command than to reach for the mouse. Many people
who are used to the good old days of the command prompt find themselves right at home with the command
window, but whether or not you are one of these people, I encourage you to explore its functionality.
The main keystroke to remember is Ctrl-Alt-A (View.CommandWindow); this is the shortcut to open the
command window.
The open command is the first command I am going to cover. Using the open command, you can open any file
in either the filesystem or the current solution. (I think the real added value here is opening a file in the current
solution, since the command window provides IntelliSense.) Figure shows the command window and the
IntelliSense available for the open command.



This might not seem like much, but if you have a dozen projects with hundreds of files, this becomes much faster
than digging through the Solution Explorer with your mouse.
You can use any Visual Studio command directly through the command window (through this book, whenever we
mention a keyboard shortcut, we've also been mentioning the command). Any command can be used through
the command window.
Twenty of the most useful commands are shown in Table . You can either type the full command or use the
alias.



When in doubt, you can sometimes fall back on old MS-DOS command prompt habits: for instance, the
command cls will clear the command window. You can find a complete list of commands in the Tools
Options Keyboard screen
Read More

Start Visual Studio from RUN

We can start visual studio from RUN by following steps:-
1. click start menu. (or press window key + R and go to step 3)
2. click on RUN.
3. type DEVENV in RUN and press ok or hit enter.

we can use this to improve speed of opening visual studio by following steps:-

* in above steps type "devenv /nosplash" instead of only DEVENV. this will open visual studio without its splash screen. and without splash screen it will be opened fast.
Read More

Turn Off Dynamic Help

By Turn off dynamic help we can improve speed of visual studio.
Another issue that Visual Studio .NET helped to resolve was Dynamic Help starting during startup.
Dynamic Help is another part of Visual Studio that tends to slow everything down. It is a good idea to make sure
the Dynamic Help window is not open when you start up Visual Studio—this is done by simply making sure the
window is closed when you close Visual Studio.
If you never really use Dynamic Help, you can disable it completely. To do this, you need to delve into the
registry and change the value of the key located here:
HKEY_CURRENT_USER\Software\Microsoft\Visual Studio\<7.1>\Dynamic Help
The name of the key is Never Show DH on F1, and you will need to change the value of this key to YES. Doing
this will disable Dynamic Help.
Read More

Disable the Start Page of Visual Studio

We can disable the start page of visual studio. its a one of the tricks which is used to improve the speed of visual studio.

The start page is the web page that is displayed by default when Visual Studio first starts up. By default, this
page shows a list of recent projects and includes tabs that list online resources and allow you to edit your Visual
Studio profile. The start page does not really add any functionality that you can't access somewhere else. The
reason the start page is both a security threat and a slowdown factor is that it launches Internet Explorer. Visual
Studio .NET 2003 fixes this issue slightly by loading Internet Explorer only if you are using a customized start
page, so needless to say, using a customized start page is discouraged.

If you don't get a lot of use out of the start page, it is easily disabled in the Options menu. While the performance
gain won't be the same between Visual Studio editions, it will be enough to be worth the effort. To disable the
start page, simply go to Tools Options, then choose General under the Environment folder (General should
be selected by default). On the right of that screen, you will see a drop-down where you can specify what Visual
Studio should do on startup. I recommend choosing Show Empty Environment; this means Visual Studio will not do anything special on startup.
Read More

Thursday, August 27, 2009

Master IntelliSense

Visual Studio can read your mind. Learn how to have Visual Studio's IntelliSense feature do lots of the
typing for you.
Even if you have used Visual Studio only a couple times, I am sure you have noticed one of its trademark
features: IntelliSense. The most popular form of IntelliSense assists you as you code by providing a list of the
members for each class immediately after you finish typing the class name (and the following period). This is not
the only form of IntelliSense though; this feature finds its way into a multitude of different areas of Visual Studio.

Complete Word
The first, and most useful, IntelliSense feature is actually just a shortcut: Ctrl-Space (Edit.CompleteWord).
By using the Ctrl-Space shortcut, you can summon IntelliSense at any point during your coding session, not just
when you finish typing a class name. This is one of the few shortcuts that can really change the way that you
write code.
If you have already starting typing when you press Ctrl-Space, Visual Studio will take one of two actions. If there
is only one object that matches what you have typed in so far, it will automatically complete the object name; for
instance, if you typed in HttpR, it would automatically complete the rest of the object name (HttpRequest). If
there are a number of objects that match what you have typed in, it will display the full list of members with the
first match highlighted. Figure shows what the listbox would look like if you only typed in the letter P.




You can also press Ctrl-Space on a blank line and be shown a complete list of members in the current context.
This is a great way to find a variable name that has slipped your mind. Figure shows an example of this.



This shortcut can be even more useful if you name all of your private member variables with a common prefix; for
instance, if all of your variables are prefixed with "_", by typing _ and then pressing Ctrl-Space, you would display
a list of all of your variables to choose from.
Read More

Block Selection

Normal text selection is done on a line-by-line basis; it is impossible to select parts of multiple lines with
normal text selection. Figure shows how it is not possible to select just the right side of the equals sign using
normal text selection. This is a drawback that most of us have become accustomed to.



Visual Studio has a feature that allows you to get around this limitation. By holding the Alt key while selecting
text, you trigger block selection, which allows you to select text regardless of what line it is on. Figure shows
how block selection can be used to select only text to the right of the equals sign.



Block selection can be used to select any amount of text in a block, as opposed to line by line. You can use block
selection whether you select text with the mouse or the keyboard (hold down Alt and Shift, and press the arrow
keys to perform a block selection with the keyboard).
When pasting block selections, Visual Studio will insert each line of the block onto a subsequent existing line,
unlike normal selections where new lines will be inserted. Thus, it is important to be sure that the destination for
your block selection is the same number of lines as the source.
Read More

Line-Based Cut and Paste

The clipboard ring is not the only copy and paste feature in Visual Studio; a number of shortcut keys allow you
to copy and paste code even faster.
Most applications rely on you selecting which text you want to cut, copy, or delete. Visual Studio makes the very
simple assumption that if you have not selected any text that you want to cut, copy, or delete, the editing action

will be performed on the entire current line. If you wanted to move one line below another line, you could move
the cursor to the first line, press Ctrl-X (Edit.Cut) to cut the line, press the down arrow to move to the next line
down, and then press Ctrl-V (Edit.Paste) to paste the entire line. Other shortcuts like Ctrl-C (Edit.Copy) and
Ctrl-L (Edit.LineCut) follow this same rule and allow you to copy or delete the current line by simply pressing the
shortcut keys without selecting any text. Any time you can avoid reaching for the mouse to select text is time
saved.
Read More

Clipboard Ring

When you copy and paste text in any application, you are usually limited to copying and pasting one item at a
time. If you want to copy two separate sentences, you have to copy the first one, paste it, then come back and
repeat this for the next sentence. This can become tedious when you have 10 different things to copy and they
reside in 10 different places in the document. You end up switching back and forth between the two documents
10 times, once for each sentence you want to copy.
The clipboard ring eliminates this limitation. The clipboard ring allows you to cut or copy up to 20 selections and
access them using a keyboard shortcut. Here is the process for using the clipboard ring:
Copy (Ctrl-C, Edit.Copy) or Cut (Ctrl-X, Edit.Cut) up to 20 text selections, one after the other.
These selections are organized as a last-in-first-out (LIFO) stack. That is, the last item you cut or copy
will be the top item on the clipboard ring.
1.
Press Ctrl-Shift-V to paste the first selection (the item on the top) from the clipboard ring into your
document.
2.
If you don't want to paste the first selection, press Ctrl-Shift-V (Edit.CycleClipboardRing) again, and the
first thing you pasted will be replaced with the next selection from the clipboard ring. For example, if you
wanted to paste the fourth item in the clipboard ring, you would simply press Ctrl-Shift-V four times. If you want to paste the same item more than once, simply pressing Ctrl-V (Edit.Paste) after the first
time will work, since it will now be the current item on the clipboard.
Instead of moving between two documents a number of times, copying and pasting different selections, you can
first copy all of the selections from the first document, then go to the second document and, using the clipboard
ring, paste all of those selections. The clipboard ring also comes in handy when you have two or more separate
things that you need to paste multiple times; using the clipboard ring, you can switch back and forth between
these items easily.



While the Clipboard Ring tab is a good way to get a better understanding of the clipboard ring, it is not as efficient
as the shortcut keys. Visual Studio .NET 2003 users will find that the Clipboard Ring tab is absent in Visual
Studio 2005, so it is best to use the shortcut keys instead of the Toolbox tab.
You can also view the current contents of the clipboard ring by selecting the Clipboard Ring tab in the Toolbox
dialog. This tab, shown in Figure , displays all of the selections currently living in the clipboard ring and allows
you to drag the selections to paste them into your document.
Read More

Monday, August 10, 2009

To select the text of textbox by code when focus enter to textbox

private void textbox_Enter(object sender, EventArgs e)
{
((TextBox)sender).SelectAll();
}
Read More
Powered By Blogger · Designed By Seo Blogger Templates