Saturday, January 12, 2013

Variables and Parameters in C#.NET


Variables represent storage locations, and every variable has a type that determines what values can be stored in the variable. Local variables are declared in function members (for example, methods,  properties, and indexers).

A local variable is defined by specifying the following:
  •  A type name
  •  A declarator that specifies the variable name and an optional initial value

The following code shows three local variable definitions:

int x;
int y = 7;
int z = 14;

A local variable declaration can also include multiple declarators. For example:

int x, y = 7, z = 14;

It is absolutely essential that a variable be assigned before its value can be obtained. If not, a compiler error will be generated. As an example, trying to compile the following code would result in a compiler error (because the line highlighted is using a variable that has not yet been assigned a value):

class Test
{
static void Main()
{
int x;
int y = 7;
int z = x + y;
}
}

A field is a variable associated with a class or struct or an instance of a class or struct. A field declared with the static modifier defines a static variable, and a field declared without this modifier defines an instance variable. A static field is associated with a type, and an instance variable is associated with an instance.

using Books.Data;

class Titles
{
private static DataSet ds;
public string Title;
public decimal Price;
}

In the preceding example, there is a class that has a private static variable and two public instance variables. Formal parameter declarations are also used to define variables. There are four different kinds:
  •  Value parameters. Used for “in” parameter passing, where the value of an argument is passed into a method
  •  Reference parameters. Used for “by reference” parameter passing, where the parameter acts as  an alternative name for a caller that provided the argument
  •  Output parameters. Similar to a reference parameter, except that the initial value of the argument  provided by the caller is not important
  • Parameter arrays. Declared with a params modifier. There can be only one parameter array for any method, and it will always be the last parameter specified.

No comments:
Write comments
Recommended Posts × +