Friday, July 1, 2016

CSharp Literals

What are literals in C#



Define a literal

A literal is a fixed value. You can use it on the right hand side of an expression. You cannot assign a value to a literal. 

We discussed Left Hand Side (LHS) and Right Hand Side (RHS) in an earlier post. They are different from variables in that the variables can be placed on either side of the expression whereas the literals can be only on the right side of an expression.

int x = 3; //This is valid

3 = x; //This is not valid 


Types of Literals

Basically we can classify literals into numeric and non numeric literals.

String Literals

String literals are enclosed in double quotes "". Any number of characters can be placed withing the opening and closing quotation marks as long as you don't reach the memory limit of the data type.
string myName = "Aamir Mehmood";

string address = @"Unit# 123, 21 Street, \nOntario, \nCanada";

String literals can also contain escape sequence within quotes as shown above. 


Numeric Literals

When using numerical literals you use suffixes to specify the type of the value. Integer literal are suffixed with u, U, l, L, d, D, f, F, m, M


  • u and U are used for unsigned numbers
  • l or L are used for long numbers
  • d or D are used for double numbers
  • m or M are used for decimals numbers
  • f or F are used for floating point numbers


While the number 7 is an integer you can make it a double like so:

double y = 7D;




Other examples of numeric literals:


uint a = 45u;
long b = 479387L;
decimal g = 34.34m;


A short note on floating point literls is that the floating point numbers can be expressed in their decimal equivalent or exponential equivalent forms.



Example of decimal equivalent form


float fx = 3.4F; //If F is not applied the compiler will complain that you cannot assign 3.5, which is by default a double, to a float variable.

Example of exponential equivalent form

float ex = 1E-9;




No comments:

Post a Comment