Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Constants & Literals in C#

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

As the name suggests, Literals (often referred to as constants) are the data items that never change their value during a program run.So these are the fixed values which can be of any data type like Integer constant or Character constant. These are treated similarly like the variables but they cannot change their values through out the program. These are predefined so that we can easily implement them. Following are some of the types of literal.

  • Integer literal
  • Floating Point literal
  • Character literal
  • String literal
  • Bool literal
  • Null literal

Before we discuss about the types of literals we’ll see differences between constants and literal.

Recommended Topic, Palindrome in C#, singleton design pattern in c# and Ienumerable vs Iqueryable.

Difference between Constant and Literal

A literal is a value that is stated exactly as it is. Literals include the number 44 and the text "Hello Ninja." 

A constant is a data type that may be used to replace a literal. Constants are used when the same, unchanging value is utilised several times throughout the programme. For example, if you have a constant named PI that you'll be reusing in your programme to determine the area, circumference, and other properties of a circle, this is a constant since you'll be recycling its value. However, when you declare it as: 

const float PI = 3.141; 

You're using a literal of 3.141. It has no memory address of its own and just resides in the source code.

Mow we move to discuss types of literals.

Integer Literals

Integer literals are pure integers that do not include any fractional parts. This is specified under the integer literal rule. An integer constant must have at least one digit and no decimal point. It can have either a + or a - symbol. A number that lacks a sign is presumed to be positive. Commas are not permitted in integer constants.

Following are the types of integer literals

Decimal literals (Base 10)

Decimal literals are those literals that consist sequence of digits but shouldn't start with 0.

//integer literal - Decimal literal

int x=89;

Binary literals (Base 2)

Binary literals are those literals that consist sequence of digits and must start with 0b. Just like the Binary language, only 0s and 1s are allowed.

//integer literal - Binary literal (decimal 8 is written as 1000 in binary)

int x=0b1000;

Octal literals (Base 8)

Octal literals are those literals that consist sequence of digits and must start with 0.

//integer literal - Octal literal (decimal 8 is written as 10 as octal integer)

int x=010;

Hexadecimal literals (Base 16)

Hexadecimal literals are those literals that consist sequence of digits and must start with 0x or 0X. Since C# is a case-sensitive language but here is an exception.

/*integer literal - Hexadecimal literal (decimal 12 is written as XC as hexadecimal integer)*/

int x=0XC;

The suffix u/U and l/L in front of any integer literals depict its type, which is unsigned or long, respectively.

Now, it’s time to verify our learning using code.

// A C# program to show the use of Integer Literals
using System;
class CodingNinjas
{
// Main
public static void Main(String[] args)
{

// decimal literal
int q = 35;
// octal literal
int w = 015;
// Hexa-decimal literal
int e = 0xD;
// binary literal
int r = 0b0100;

Console.WriteLine(q);
Console.WriteLine(w);
Console.WriteLine(e);
Console.WriteLine(r);
}
}

Output:

35

13

13

4

Now let’s move to our next type of literal.

Floating Point literal

Floating-point literals are written in two types. One form is called fractional form. It consists of unsigned and signed digits. It must have a digit before the decimal point and one digit after the decimal point. A +/- sign may be there to define its sign. Without the sign, it is considered positive. 

The other type is of exponent form, which has two parts: exponent and mantissa. Mantissa must be an integer followed by the exponent E/e, which must be an integer.

//Examples of floating-point literal

double a=2.0;            //valid

double b=-12.0;         //valid

double c=3;               //invalid: no decimal

double d=17/4;          //invalid: / is illegal symbol

double e=52E05;       //valid

double f=173E-8;       //valid

double g=0.34E07;    //valid

double f=100.E8;       //invalid: a digit must follow decimal point

double g=0.34E2.3;   //invalid: Exponent can’t have fractional part

double h=.43E-4;       //invalid: digit is missing in front of decimal point

Now, it’s time to verify our learning using code.

// A C# program to show the use of floating-point literals
using System;
class CodingNinjas
 {
// Main 
public static void Main(String[] args)
{
// decimal literal
double q = 45.30;
// decimal literal
double w = 016.3E6;
Console.WriteLine(q);
Console.WriteLine(w);
}
}

Output:

45.3

16300000

Now, it's time to move to the next type of literal

Character literal

Character literal is the single character literal which is enclosed in single quotation marks such as 'x'. It can be either a plain character or Unicode representation or escape sequence. These are denoted by char data type.

Plain characters are simple characters enclosed in single quotation marks. 

//character literal

char ch=‘a’;

Unicode representation is also enclosed in single quotation marks. It’s represented as ‘\uxxxx’. The xxxx are hexadecimal numbers.

//character literal of Unicode. Here 0065 is Unicode of e.

char ch= ‘u0065’ 

Character constants in C# can contain certain escape sequences. 

Escape sequences are those that cannot be typed directly from the keyboard, such as backspace, tabs, carriage return, and so on. A backslash (\) followed by one or more characters denotes an escape sequence.

Escape Sequence Meaning 
\\ \character
\’ ‘character
\” “character
\? ?character
\b Backspace
\a Alert or bell
\f Form feed
\r Carriage return
\v Vertical return
\n Newline
\ooo Octal number of one or more digits
\xhh… Hexadecimal number of one or more digits

Now, we'll move to the next type of literal, i.e., string literal.

String literal

String literal is a sequence of characters enclosed by double quotations (“ ”) or (@ “ ”). 

//String literal

string a1= “Hello Detective”;

string a2= @“Hello Detective”;

Now, it’s time to verify our learning using code.

// A C# program to show the use of char literals
using System; 
class CodingNinjas 
{ 
// Main
public static void Main(String[] args)
{ 
// character literal in single quote
char ch = 'q'; 
// Unicode representation
char c = '\u0069';
Console.WriteLine(ch);
Console.WriteLine(c);
// Escape sequence literal
Console.WriteLine("Hello\n\nDetective\t!");
}
}

 

Output:

q

i

Hello

Detective     !

We are moving to the next type of literal.

Bool literal

The bool literal in C# is used to represent one of the two boolean values, i.e., true (boolean true) or false (boolean false). Internally boolean true has a value of 1, and boolean false has a value of 0.

//bool literal

bool x=true;

bool y=false;

Now, it’s time to verify our learning using code.

// A C# program to show the use of String literals
using System; 
class CodingNinjas 
{ 
// Main
public static void Main(String[] args)
{
String s1 = "Hello Detective!";
String s2 = @"Hello Detective!";
                       // String s3 = Hello;
                       //will couse error because 
                       //Hello is not enclosed in “”
                       //and it will be treated as variable.
Console.WriteLine(s1);
Console.WriteLine(s2);
}
}

Output:

Hello Detective!

Hello Detective!

We are moving to our final type of literal.

Null literal

The null keyword is a literal that denotes a null reference, which means it does not relate to any object. The default value of reference-type variables is null. Except for nullable value types, ordinary value types cannot be null.

// A C# program to show the use of Null literal
using System;
class CodingNinjas
{
    static void Main()
    {
        string[] array = { "q", "w", "e","r","t","y" };
        //if null literal is not used then output will be 6 i.e., value of array
        array = null;
        if (array == null)
        {
            Console.WriteLine("Array is null");
        }
        else 
        {
            int value = array.Length;
            Console.WriteLine(value);
        }
    }
}

Output:

Array is null

Now it’s time to munch on some FAQs.

FAQs

  1. What is an integer literal?
    Integer literals are full integers that do not include any fractional parts. This is specified under the integer literal rule. An integer constant must have at least one digit and no decimal point.
  2. What is a character literal?
    A character literal is the single character literal which is enclosed in single quotation marks such as 'x'. It can be either a plain character or Unicode representation or escape sequence. These are denoted by char data type.
  3. What is an escape sequence?
    Escape sequences are those that cannot be typed directly from the keyboard, such as backspace, tabs, carriage return, and so on. A backslash (\) followed by one or more characters denotes an escape sequence.
  4. What is Bool literal?
    The bool literal in C# is used to represent one of the two boolean values, i.e., true (boolean true) or false (boolean false). Internally boolean true has a value of 1, and boolean false has a value of 0.
  5. What is Null literal?
    The null keyword is a literal that denotes a null reference, which means it does not relate to any object. The default value of reference-type variables is null. Except for nullable value types, ordinary value types cannot be null.

Now, it’s time to summarise the learning.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Key Takeaways

In this article, we have extensively discussed C# constant and literal. We started with integer literals and their types, i.e., decimal, octal, hexadecimal and binary. Then moved to floating-point literals. Then we learnt about character literal and string literal. After that, we learnt about string literal and moved to bool literal. Then we learnt about null literal. After each type of literal, we practised with an example. In the end, we went through some FAQs.

Ninjas! Go through the differences between C++ and C# to understand the differences between C++ and C#.

We hope that this blog has helped you enhance your knowledge regarding Type conversion in C# and if you would like to learn more, check out our articles on Coding Ninjas Studio. Do upvote our blog to help other ninjas grow. Happy Coding!

Topics covered
1.
Introduction
1.1.
Difference between Constant and Literal
1.2.
Integer Literals
1.2.1.
Decimal literals (Base 10)
1.2.2.
Binary literals (Base 2)
1.2.3.
Octal literals (Base 8)
1.2.4.
Hexadecimal literals (Base 16)
1.3.
Floating Point literal
1.4.
Character literal
1.5.
String literal
1.6.
Bool literal
1.7.
Null literal
2.
FAQs
3.
Key Takeaways