top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C# Keywords and Escape Sequences

0 votes
353 views

Keywords and Escape Sequences

Keywords

Keywords are reserved words and are separately compiled by the compiler. They convey a predefined meaning to the compiler and hence cannot be created or modified. For example, int is a keyword that specifies that the variable is of data type integer. You cannot use keywords as variable names, method names or class names unless you prefix the keywords with the “@” character.

The table consist the keywords used in c#,

abstract

bool

break

byte

case

catch

char

class

const

continue

default

double

enum

else

false

finally

float

for

foreach

goto

if

int

interface

long

namespace

new

public

private

protected

return

sbyte

short

static

string

struct

switch

throw

true

try

ushort

void

while

 

Need of escape Sequence Character

Consider a payroll system of an organization. One of its functions is to display the monthly salary as output with the salary display on the next line. The programmer wants to write the code in such a way that the salary is always printed on the next line irrespective of the length of string to be displayed with the salary amount. This is done using escape sequences.

 

Defination

An escape sequence character is a special character that is prefixed by a backslash (\). Escape sequence characters are used to implement special non-printing characters such as a new line, a single space or a backspace. These non-printing character are used while displaying formatted output to the user to maximize readability.

The backslash character tells the compiler that the following character denotes a non-printing character. For example, \n is used to insert a new line similar to the Enter key of the keyboard.

There are multiple escape sequence characters in C# that are used for various kinds of formatting. The table shown below displays the escape sequence characters and their corresponding non-printing characters in C#.

Escape Sequence Characters

Non-Printing Characters

\’

Single quote, needed for character literals.

\”

Double quote, needed for string literals

\\

Backslash, needed for string literals.

\0

Unicode character 0.

\a

Alert

\b

Backspace.

\f

Form feed.

\n

New line.

\r

Carriage return

\t

Horizontal tab.

\v

Vertical tab.

\xhh

Matches an ASCII character using hexadecimal representation (exactly two digits). For example, \x61 represents the character ‘a’.

\uhhhh

Matches a unicode character using hexadecimal representation (exactly four digits). For example, the character #u0020 represents a space.

 

The following snippet demonstrates the use of unicode charaacters.

String str = “#u0048#u0065#u006C#u006C#u006F;

Console.Write(“\t” + str + “!\n”);

Console.WriteLine(“David\u0020\”2007\” “);

Output:

            Hello!

David “2007”

In the above code, the variable str is declared as type string and stores unicode characters for the letters H, e, l, l and o. The method uses the horizontal tab escape sequence character to display the output leaving one tab space. The new line escape sequence charactter used in the string of the method displays the output of the next statement in the next line. The next statement uses the WriteLine() method to display David “2007”. The string in the method  specifies the unicode character to display to display a space between “David” and “2007”. 

For More Go Through This Video:

posted Aug 9, 2017 by Piyush Jain

  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

Constants and Literals

In C# , you can declare constants for all data types. You have to initialize a constant constant at the time of its declaration. Constants are declared for value types rather than for reference  types. To declare an identifier as a constant, the const keyword is used in the identifier declaration. The compiler can identify constants at the time of compilation because of the const keyword.

Syntax:

const <data type> <identifier name> =  <value>;

Where,

const: keyword denoting that the identifier is declared as const.

Data type: Data type of constant.

Identifier name: Name of the identifier that will hold the constant.

Value: Fixed value that remains unchanged throughout the execution of the code.

Example:

The following code declares a constant, _pi , and a variable, radius, to calculate the area of the circle.

const float _pi = 3.14F;

float radius= 5;

float area = _pi * radius * radius;

Console.WriteLine (“Aread of the circle is “ +area);

In the above code, a constant called _pi  is assigned the value 3.14 which is a fixed value. The variable, radius, stores the radius of the circle. The code calculates the area of the circle and displays it as the output.

Using Literals

A literal is a static value assigned to variables and constants. You can define literals for any data types of C#. Numeric literals might suffix which a letter of the alphabet to indicate the data type of the leteral. This letter can be either in upper or lower case. For example, in the following declaration, string bookName = “Csharp”, Csharp is a literal assigned to the variable bookName of type string.

In C#, there are six types of literals. These are:

                                        

  • Boolean Literal: Boolean literals have two values, true or false. For example,

bool val = true;

where, true: Is a Boolean literal assigned to the variable val.

 

  • Integer Literal: An integer literal can be assigned to int, uint, logn or ulong data types. Suffixes for integer literals include U, L, UL or LU. U denotes uint or ulong, L denotes long. UL and LU denote ulong. For example,

long val = 53L;

where,

53L: Is an integer literal assigned to the variable val.

 

  • Real Literal: A real literal is assigned to float, double (default), and decimal data types. This is indicated by the suffix letter appearing after the assigned value. A real literal can be suffixed by F, D or M. F denotes float, D denotes double and M denotes decimal. For example,

float val = 1.66F;

Where,

1.66F: Is a real literal assigned to the variable val.

 

  • Character Literal: A character literal is assigned to a char data type. A character literal is always enclosed in single quotes. For example,

Char val = ‘A’;

Where,

A: Is a character literal assigned to the variable val.
 

  • String Literal: There are two types of string literal in c#, regular and verbatim. A regular string literal is a standard string . A verbatim string literal is similar to a regular string literal but is prefixed by the @ character. A string literal is always enclosed in double quotes. For example,

string mailDomain = “@gmail.com”;

Where,

@gmail.com: Is a verbatim string literal.

Null Literal: The null lieteral has only one value, null. For example,

string email = null;

Where,

Null: specifies that email does not refer to any objects (reference).

READ MORE

Classification

Reference data types store the memory reference of other variables. These other variable hold the actual values. Reference type can be classified as:

Object: Object is a built-in reference data type. It is a base class for all predefined and user-defined data types. A class is a logical structure that represents a real world entity. This means that the predefined and user-defined data types are created on the object class.

String: String is a built-in reference type. String type signifies Unicode character string values. Once string are created, they cannot be modified.

Class: A class is user-defined structure that contains variables and methods. For example, the Employee class can be a user-defined structure that can contain variables such as empsalary, empname, and empAddress. In addition, it can contain methods such as CalculateSalary() , which returns the net salary of an employee.

Delegate: A delegate is a user-defined reference type that stores the reference of one or more methods.

Interface: An interface is a type of user-defined class that is used for multiple inheritance.

Array: An array is user-defined data structure that contains values of the same data type, such as marks of students.

Variable Naming Rules

A variable needs to be declared before it can be referenced. You need to follow certain rules while declaring a variable:

  • A variable name can begin with an upper case or a lower case letter. The name can contain letters, digits and the underscore character(_).
  • The first character of the variable name must be a letter and not a digit. The underscore is also a legal first character, but it is not recommended at the beginning of a name.
  • C# is a case-sensitive language; hence variable names count and count refer to two different variables.
  • C# keywords cannot be used as variable names. If you still need to use a c# keyword prefix it with the ‘@’ symbol.

Note: Microsoft recommends camelcase notation for c# variable names. You should not use underscores and must ensure that the first letter of the identifier is in lowercase. In addition, you must capitalize the first letter of each subsequent word of the identifier. For example, consider the following variable declarations:

Int totMonths = 12;

String empName = “John Ferb”;

Bool statusInfo = true;

 

Create and use variables

A variable’s type and identifier (name ) need to be mentioned when you declare a variable. This tells the compiler the name of the variable and the variable and the type of data the variable will store. If you attempt to use an undeclared variable, the compiler will generate and error message. The table given below displays a list of valid and invalid variable names in c#.

Variable Name

Valid/Invalid

Employee

Valid

student

Valid

_Name

Valid

Emp_Name

Valid

@goto

Valid

static

Invalid as it is a keyword

4myclass

Invalid as a variable cannot start with a digit

Student&Faculty

Invalid as a variable cannot have the special character &

Note: When you declare a variable, the computer allocates memory for it. Hence, to avoid wasting computer memory, it is recommended to declare variables only when required.

READ MORE

Variable and Data Types in C#

A variable is an entity whose value can keep changing. For example, the age of a student, the age of a student, the address of a faculty member and the salary of an employee are all examples of variables.

  

In C#, a variable is a location in the computer’s memory that is identified by a unique name and is used to store a value. The name of the variable is used to access and read the value stored in it. Different types of data such as a character, an integer or a string can be stored in variables. Based on the type of data that needs to be stored in variable, variables can be assigned different data types.

Using variables

In C# , memory is allocated to a variable at the time of its creation. During creation, a variable is given a name that uniquely identifies the variable within its scope. For example, you can create a variable called empName to store the name of an employee.

You can initialize the variables at the time of creating the variable or at a later time. Once initialized, the value of a variable can be changed as required.

In c#, variable enable you to keep track of data. When you are referring to a variable, you are actually referring to the value stored in that variable.

The following syntax is used to declare variable in c#,

<datatype> <variableName>;

Where,

Datatype: Is a valid data type in C#.

VariableName: Is a valid variable name.

Data Types

You can store different types of values such as numbers, characters or strings in different variables. But the compiler must know what kind of data a particular variable is expected to store. To identify the type of data that can be stored in a variable, c# provides different data types.

When a variable is declared, a data type is assigned to the variable. This allows the variable to store values of the assigned data types. In C# programming language, data types are divided into two categories. These are:

 

Value Types: variable of value types store actual values. These values are stored in a stack. The values can be either of a built-in data type or a user-defined data type. Most of the built-in data type are value types. The value type built-in data types are int, float, double, char and bool. Stack storage results in faster memory allocation to variables of value types.

Reference Type: Variables of reference type store the memory address of other variables in a heap. These values can either belong to a built-in data type or a user-defined data type. For example, string is a built-in data type which is a reference type. Most of the user-defined data types such as class are reference types.

Predefined Data Types

The predefined data types are referred to as basic data types in c#. These data types have a predefined range and size. The size of the data type helps the compiler to allocate memory space and the range helps the compiler to ensure that the value assigned is within the range of the variable’s data type.

The predefined data types in c# is given below:-

Data Type

Size

Range

byte

Unsigned 8-bit integer

0 to 255

short

Signed 16-bit integer

-32, 768 to 32,767

int

Signed 32-bit integer

-2,147,483,648 to 2,147,483,647

long

Signed 64-bit integer

-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

float

32-bit floating point with 7 digits precisions

±1.5e-45 to ±3.4e38

double

64-bit floating point with 15-16 digits precision

±5.oe-324 to ± 1.7e308

decimal

128-bit floating point with 28-29 digits precision

±1.0  x 10e-28 to ±7.9 x 10e28

char

Unicode 16-bit character

U+0000 to U+ffff

bool

Stores either true or false

True or flase

 

READ MORE
...