Thursday, June 28, 2012

Output Parameters

Is it possible to have multiple return statements within a function ??? Obviously the answer would be NO !!!. What if you need to get multiple values returned ??? Output Parameters would be the solution.
Using Output Parameters additional data can be returned from a method. The following example demonstrate the use of Output Parameters.


Note: When an Output Parameter is declared in a method, it should be assigned value before leaving the method scope.

Named Arguments

When invoking a method can you even think of messing up the order of the parameters  ??? YES, you can. ;) Thanks to Named Arguments in C#.
Using these you can specify parameters by a name and supply arguments in an order that differs from order of the parameters in the method signature. The following example helps you to understand this more.

// Method declaration
void NameArgs(int _first,int _second,int _thrid) 
{
...
}
// Method invocation
NameArgs(_third:10,_second:5,_first:3);

Optional Parameters

When invoking a function, can you not pass in values as mentioned in the method signature and pass in only the values you need ???
Sorry !!! you cannot do that. But what if you need to do so ??? Optional Parameters is the answer. Optional Parameters allows you to define a method and provide default values for parameters in the parameter list.
Note : All the declared optional parameters should be at the end of the parameter list. In other words it should be declared after the normal parameters.
// Method declaration
int OptionalTest (int a, int b, int c = 10)
{
...
}
// Method invocation
int _val = OptionalTest(10, 5); // ' c ' would be 10
int _val = OptionalTest(10, 5, 25); // ' c ' would be 25

Jagged Arrays

Jagged array is an array of arrays. When declaring and initializing a jagged array, the size of the first array should be specified. But must not specify the sizes of the other arrays that are contained in this array.
string [][] _str = new string [10][];
_str[0] = new string [5];
_str[1] = new string [4];

String Immutability - String Builder

First of all Immutable means - Once created cannot be changed and Mutable means liable to change. Strings are immutable. The best example to demonstrate this would be a string concatenation example. When concatenating a string, a new string object is created and the variable references to the newly created object and the previously created object will be sent for garbage collection. This scenario would be explained further using the following code snippets.


To avoid this situation of StringBuilder class can be used as follows,