top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

var - Implicit typed local variable in C#

0 votes
168 views

C# 3.0 introduced the implicit typed local variable "var". Var can only be defined in a method as a local variable. The compiler will infer its type based on the value to the right of the "=" operator.

Example: Explicitly typed variable

int i = 100;// explicitly typed 
var i = 100; // implicityly type

The following example shows how var can have a different type based on its value:

Example: Implicit typed variable - var

static void Main(string[] args)
{
    var i = 10;
    Console.WriteLine("Type of i is {0}",i.GetType().ToString());

    var str = "Hello World!!";
    Console.WriteLine("Type of str is {0}", str.GetType().ToString());

    var d = 100.50d;
    Console.WriteLine("Type of d is {0}", d.GetType().ToString());

    var b = true;
    Console.WriteLine("Type of b is {0}", b.GetType().ToString());
         
}

Output:

Type of i is System.Int32 
Type of str is System.String 
Type of d is System.Double 
Type of b is System.Boolean

Var can be used in the following different contexts:

  • Local variable in a function
  • For loop
  • Foreach loop
  • Using statement
  • As an anonymous type
  • In a LINQ query expression

Points to Remember :

  1. var can only be declared and initialized in a single statement. Following is not valid: 
    var i; 
    i = 10;
  2. var cannot be used as a field type at the class level.
  3. var cannot be used in an expression like var i += 10;
  4. Multiple vars cannot be declared and initialized in a single statement. For example, var i=10, j=20; is invalid.
posted Feb 2, 2017 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

Standard Date and Time Format Specifiers

 A Date and time format specifier is a special character that enables you to display the date and time values in different formats. For example, you can display a date in mm-dd-yyyy format and time in hh:mm format. If you are displaying  GMT time as the output, you can display the GMT time along with the abbreviation GMT using date and time format specifiers.

The date and time format specifiers allow you to display the date and time and time in 12-hour and 24-hour formats.

The following is the syntax for date and time format specifiers.

Console.WriteLine(“{format specifier}”, <datetime object>);

Where,

Format specifier: Is the date and time format specifier.

Datetime object: Is the object of the DateTime class.

Some Standard date and time specifiers are used in the Console.WriteLine() method with the datetime object. To create the datetime object, you must create an object of the DateTime class and initialize it. The formatted date and time are always displayed as string in the console window.
                                                                                                      

 

The table shown below displays some of the standard date and time format specifiers in C#.

Format Specifier

Name

Description

  D

Long date

Displays date in long date pattern. The default format is “dddd*, MMMM*, dd, yyyy”.

  d

Short date

Displays date in short date pattern. The default format is “mm/dd/yyyy”

  f

Full date/time (short time)

Displays date in long date and short time patterns,, separated by a space. The default format is “dddd*”, MMMM* dd, yyyy HH*:mm*”.

  F

Full date/time (long time)

Displays date in long date and long time patterns, separated by a space. The default format is “dddd*, MMMM* dd,,yyyy HH*: mm*: ss*”.

  G

General date/time (short time)

Displays date in short date and short time patterns, separated by a space. The default format is “MM/dd/yyyy  HH*:mm*”.

 

The following snippet demonstrates the conversion of a specified date and time using the d,D,f,F and g date and time format specifiers:-

DateTime dt =  DateTime.Now;

//Returns short date (MM/DD/YYYY)

Console.WriteLine("Short date format (d): {0:d}",dt);

//Returns long date (Day, Month Date, Year)

Console.WriteLine("Long date format (D) : {0:D}", dt);

//Returns full date with time and without seconds

Console.WriteLine("Full date with time without seconds (f) : {0:f}", dt);

//Returns full date with time and with seconds

Console.WriteLine ("Full date with time with seconds (F) : {0:F}", dt);

//Returns short date and short time without seconds

Console.WriteLine ("Short date and short time without seconds (g) : {0:g}", dt);

 

Output:

Short date format (d) : 23/06/2017

Long date format  (D) : Friday, June 23, 2017

Full date with time without seconds (f) : Friday, June 23, 2017 11:12 AM

Full date with time with seconds (F): Friday, June 23, 2017 11:12:34 AM

Short date and short time without seconds (g): 23/06/2017 11:12 AM

 

More Standard Date and Time Format Specifiers

Format Specifier Name   Description
  G General date/time (long time)  Displays date in short date and long time patterns, separated by a space. The default format is "MM/dd/yyyy HH*:mm*:ss*".
 m or M Month day Displays only month and day of the date.The default format is "MMMM* dd".
  tShort time Displays time in short time pattern.The default format is "HH*:mm*".
  TLong time Displays time in long time pattern. The default format is "HH*:mm*:ss*".
 y or YYear month pattern Displays only month and year from the date.he default format is "YYYY MMMM*".
   

 

The following snippet demonstrates the conversion of a specified date and time using the G,m,t,T :-

DateTime dt = DateTime.Now;

//Returns short date and short time with seconds

Console.WriteLine ("Short date and short time with seconds (G) : {0:G}",dt);

//Returns month and day -M can also be used 

Console.WriteLine ("Month and day (m) : {0:m}", dt);

//Returns short time 

Console.WriteLine("Short time (t) : {0:t}", dt);

 

//Returns short time with seconds

Console.WriteLine("Short time with seconds (T) : {0:T}", dt);

//Returns year and month -Y also can be used 

Console.WriteLine ("Year and Month (y): {0:y}" dt);

Output:

Short date and short time with seconds (G): 23/06/2017 11:40:55 AM

Month and day (m) : June 23

Short time (t) : 11:40 AM

Short time with seconds (T): 11:40:55 AM

Year and Month (y): June , 2017 

READ MORE

Define Numeric Format specifiers

Format specifiers are special characters that are used to display values of variables in a particular format. For example, you can display an octal value as decimal using format specifiers.

In C#, you can convert  numeric values in different  formats. For example, you can display a big number in an exponential form. To convert numeric values using numeric format specifiers, you should enclose the specifier in curly braces. These curly braces must enclosed in double quotes. This is done in the output methods of the console class.

The following is the syntax for the numeric format specifier

Console.WriteLine(“(format specifier)”, variable name>);

Where,

Format specifier: Is the numeric format specifier.

Variable name: Is the name of the integer variable.

Some Numeric Format Specifiers

Numeric format specifiers work only with numeric data . A numeric format specifier can be suffixed with digits. The digits specify the number of zeros to be inserted after the decimal location. For example, if you use a specifier such as c3, three zeros will be suffixed after the decimal location of the given number.

Format Specifier

Name

Description

C or c

Currency

The number is converted to a string that represents a currency amount.

D or d

Decimal

The number is converted to a string of decimal digits (0-9), prefixed by a minus sign is case the number is negative. The precision specifier indicates the minimum number of digits desired in the resulting string. This format is supported for fundamental types only.

E or e

Scientific (Exponential)

The number is converted to a string of the form “-d.ddd…e+ddd”, where each ‘d’ indicates a digit (0-9).

 

The following snippet demonstrates the conversion of a numeric value using C,D and E format specifiers.

int  num =456;

console.WriteLine (“{0:C}”, num);

Console.WriteLine (“{0:D}”, num);

Console.WriteLine (“{0:E}”), num);

Output:

$456.00

456

4.560000E+002

Format Specifier

Name

Description

F or f

Fixed-point

The number is converted to a string of the fomr “-ddd.ddd…” where each ‘d’ indicates a digit (0-9). If the number is negative, the string starts with minus sign.

N or n

Number

The number is converted to a string of the form “-d,ddd,ddd.ddd…”. If the number is negative the string starts with a minus sign.

X or x

Hexadecimal

The number is conveted to a string of hexadecimal digits. Uses “X” to produce “ABCDEF”, AND “x” to produce “abcdef”.

 

The following snippet demonstrates the conversion of the numeric value using F, N and X format specifiers.

int num =456;

Console.WriteLine(“{0:F}”, num);

Console.WriteLine(“{0:N}”, num);

Console.WriteLine(“{0:X}”, num);

Output

456.00

456.00

1CB

READ MORE

Console Output Operations

Console Operations  are tasks performed on the command line interface using executable commands. The console operations are used in software applications because these operations are easily controlled  by the operations are dependent on the input and output devices of the computer system.

A console application is one that performs operations at the command prompt. All console applications consists of three streams, which are a series of bytes. These streams are attached to the input and output devices of the computer system and they handle the input and output operations. Three streams are:

  • Standard in: The standard in stream takes the input and passes it to the console application for processing.
  • Standard out: The standard out stream displays the output o the monitor.
  • Standard err: The standard err stream displays error messages on the monitor.

                      

Output Methods

In C#, all console operations are handled by the console class of the System namespace. A namespace is a collection of classes having similar functionalities.

To write data on the console, you need the standard output stream. This stream is provided by the output methods of console class. There are two output methods that write to the standard output stream. They are:

  • Console.Write(): Writes any type of data.
  • Console.WriteLine(): Writes any type of data and this data ends with a new line character in the standard output stream. This means any data after this line will appear on the new line.

                                                       

The following syntax is used for the Console.Write() method, which allows you to display the information on the console window.

Console.Write(“<data>” + variables);

Where,

Data: Specifies strings or escape sequence characters enclosed in double quotes.

Variables: Specify variable names whose value should be displayed on the console.

The following syntax is used for the Console.WriteLine() method, which allows you to display the information on new line in the console window.

Console.WriteLine(“<data>” + variables);

The following code shows the difference between the console.write() method and Console.WriteLine() method.

Console.WriteLine(“C# is a powerful programming language”);

Console.WriteLine(“C#  is a powerful”);

Console.WriteLine(“Programming language”);

Console.Write(“C# is a powerful”);

Console.WriteLine(“Programming language”);

Output:

C# is a powrful programming language

C# is a powerful

Programming language

C# is a powerful Programming language

Placeholders

The WriteLine() and Write() methods accept a list of parameters to format text before displaying the output. The first parameter is a string containing markers in braces to indicate the position where the values of the variables will be substituted. Each marker indicates a zero-based index based on the number of variables in the list. For example, to indicates a zero-based index based on the number of variables in the list. For example, to indicate the first parameter position, you write {0}, second you write {1} and so on. The numbers in the curly brackets are called placeholders.

Example:

int number, result;

number =5;

result =100 * number;

Console.WriteLine (“Result is {0} when 100 is multiplied by {1}”,result, number);

result = 150 / number;

Console.WriteLine (“Result is {0} when 150 is divided by {1}”, +result, number);

Output:

Result is 500 when 100 is multiplied by 5

Result is 30 when 150 is divided by 5

Here, {0} is replaced with the value in result and {1} is replaced with the value in number.

READ MORE
...