The Wayback Machine - https://web.archive.org/web/20241117195022/https://www.geeksforgeeks.org/c-sharp-literals/
Open In App

C# | Literals

Last Updated : 07 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The fixed values are called as Literal. Literal is a value that is used by the variables. Values can be either an integer, float or string, etc. 

// Here 100 is a constant/literal.
int x = 100;

Literals can be of the following types: 

  • Integer Literals
  • Floating-point Literals
  • Character Literals
  • String Literals
  • Null Literals
  • Boolean Literals

Integer Literals: A literal of integer type is known as the integer literal. It can be decimal, binary, or hexadecimal constant. No prefix is required for the decimal numbers. A suffix can also be used with the integer literals like U or u are used for unsigned numbers while l or L are used for long numbers. By default, every literal is of int type. For Integral data types (byte, short, int, long), we can specify literals in the ways:

  • Decimal literals (Base 10): In this form, the allowed digits are 0-9.
int x = 101;
  • Hexa-decimal literals (Base 16): In this form, the allowed digits are 0-9 and characters are a-f. We can use both uppercase and lowercase characters. As we know that c# is a case-sensitive programming language but here c# is not case-sensitive.
// The hexa-decimal number should be prefix
// with 0X or 0x.
int x = 0X123Face;

  • Binary literals (Base 2): In this form, the allowed digits are only 1’s and 0’s.
// The binary number should be prefix with 0b.
int x = 0b101

Examples: 

045uu    // invalid: suffix (u) is repeated
0b105 // invalid: 5 is not a binary digit
0b101 // valid binary literal
456 // valid decimal literal
0x65d // valid hexadecimal literal
12356 // valid int literal
304U // valid unsigned int literal
3078L // valid long literal
965UL // valid unsigned long literal

Program:

C#




// C# program to illustrate the use of Integer Literals
using System;
 
class Geeks{
 
    // Main method
    public static void Main(String[] args)
    {
       
        // decimal-form literal
        int a = 101;
 
        // Hexa-decimal form literal
        int c = 0xFace;
       
        // binary-form literal
        int x = 0b101;
         
        Console.WriteLine(a);
        Console.WriteLine(c);
        Console.WriteLine(x);
    }
}


101
64206
5

Floating-point Literals: The literal which has an integer part, a decimal point, a fractional part, and an exponent part is known as the floating-point literal. These can be represented either in decimal form or exponential form.

Examples:  

Double d = 3.14145       // Valid
Double d = 312569E-5 // Valid
Double d = 125E // invalid: Incomplete exponent
Double d = 784f // valid
Double d = .e45 // invalid: missing integer or fraction

Program:

C#




// C# program to illustrate the use of
// floating-point literals
using System;
 
class Geeks {
 
    // Main Method
    public static void Main(String[] args)
    {
        // decimal-form literal
        double a = 101.230;
 
        // It also acts as decimal literal
        double b = 0123.222;
 
        Console.WriteLine(a);
        Console.WriteLine(b);
    }
}


Output: 

101.23
123.222

Note: By default, every floating-point literal is of double type and hence we can’t assign directly to float variable. But we can specify floating-point literal as float type by suffixed with f or F. We can specify explicitly floating-point literal as the double type by suffixed with d or D, of course, this convention is not required.

Character Literals: For character data types we can specify literals in 3 ways: 

  • Single quote: We can specify literal to char data type as single character within single quote.
char ch = 'a';

  • Unicode Representation: We can specify char literals in Unicode representation ‘\uxxxx’. Here xxxx represents 4 hexadecimal numbers.
char ch = '\u0061';// Here /u0061 represent a.

  • Escape Sequence: Every escape character can be specified as char literals.
char ch = '\n';

Escape Sequence Meaning
\\ \ character
\’ ‘ character
\? ? character
\” ” character
\b Backspace
\a Alert or Bell
\n New Line
\f Form Feed
\r Carriage Return
\v Vertical Tab
\xhh… Hexadecimal number of one or more digits

Example : 

C#




// C# program to illustrate the use of char literals
using System;
 
class Geeks {
 
    // Main Method
    public static void Main(String[] args)
    {
 
        // character literal within single quote
        char ch = 'a';
 
        // Unicode representation
        char c = '\u0061';
 
        Console.WriteLine(ch);
        Console.WriteLine(c);
 
        // Escape character literal
        Console.WriteLine("Hello\n\nGeeks\t!");
    }
}


a
a
Hello

Geeks !

String Literals: Literals which are enclosed in double quotes(“”) or starts with @”” are known as the String literals. 

Examples:  

String s1 = "Hello Geeks!";

String s2 = @"Hello Geeks!";

Program: 

C#




// C#  program to illustrate the use of String literals
using System;
 
class Geeks {
 
    // Main Method
    public static void Main(String[] args)
    {
 
        String s = "Hello Geeks!";
        String s2 = @"Hello Geeks!";
 
        // If we assign without "" then it
        // treats as a variable
        // and causes compiler error
        // String s1 = Geeks;
 
        Console.WriteLine(s);
        Console.WriteLine(s2);
    }
}


Output: 

Hello Geeks!
Hello Geeks!

Boolean Literals: Only two values are allowed for Boolean literals i.e. true and false.

Example: 

bool b = true;
bool c = false;

Program: 

C#




// C# program to illustrate the use
// of boolean literals
using System;
 
class Geeks {
 
    // Main Method
    public static void Main(String[] args)
    {
        bool b = true;
        bool c = false;
 
        // these will give compile time error
        // bool d = 0;
        // bool e = 1;
        // Console.WriteLine(d);
        // Console.WriteLine(e);
 
        Console.WriteLine(b);
        Console.WriteLine(c);
    }
}


Output: 

True
False

 



Previous Article
Next Article

Similar Reads

Binary Literals and Digit Separators in C#
Binary Literals The fixed values are called as Literal. Literal is a value which is used by the variables. Before C# 7.0 six types of literals are available that are an integer, Floating-point, Character, String, Null, Boolean literals. In C# 7.0 there is one more literal is added which is known as Binary Literal. The binary literal is used to stor
2 min read
C# Tutorial
In this C# (C Sharp) tutorial, whether you’re beginner or have experience with other programming languages, our free C# tutorials covers the basic and advanced concepts of C# including fundamentals of C#, including syntax, data types, control structures, classes, and objects. You will also dive into more advanced topics like exception handling, and
8 min read
ASP.NET Interview Questions and Answer
ASP.NET is a popular framework by Microsoft for building fast and scalable web applications. It allows developers to create dynamic websites, services, and apps, using server-side code and offering a user-friendly experience. Trusted by companies like Microsoft, Dell, and Accenture, ASP.NET is used to build many enterprise-level applications and we
15+ min read
C# Interview Questions and Answers
C# is the most popular general-purpose programming language and was developed by Microsoft in 2000, renowned for its robustness, flexibility, and extensive application range. It is simple and has an object-oriented programming concept that can be used for creating different types of applications. Here, we will provide 50+ C# Interview Questions and
15+ min read
Program to calculate Electricity Bill
Given an integer U denoting the amount of KWh units of electricity consumed, the task is to calculate the electricity bill with the help of the below charges: 1 to 100 units - [Tex]Rs. 10/unit[/Tex]100 to 200 units - [Tex]Rs. 15/unit[/Tex]200 to 300 units - [Tex]Rs. 20/unit[/Tex]above 300 units - [Tex]Rs. 25/unit[/Tex] Examples: Input: U = 250 Outp
9 min read
Introduction to ASP.NET
ASP.NET is a web application framework designed and developed by Microsoft. ASP.NET is open source and a subset of the .NET Framework and successor of the classic ASP(Active Server Pages). With version 1.0 of the .NET Framework, it was first released in January 2002. So a question comes to mind that which technology we were using before the year 20
5 min read
Garbage Collection in C# | .NET Framework
Garbage collection is a memory management technique used in the .NET Framework and many other programming languages. In C#, the garbage collector is responsible for managing memory and automatically freeing up memory that is no longer being used by the application. The garbage collector works by periodically scanning the application's memory to det
8 min read
HashSet in C# with Examples
In C#, HashSet is an unordered collection of unique elements. This collection is introduced in .NET 3.5. It supports the implementation of sets and uses the hash table for storage. This collection is of the generic type collection and it is defined under System.Collections.Generic namespace. It is generally used when we want to prevent duplicate el
6 min read
C# Dictionary with examples
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature means the size of the dictionary is growing
5 min read
Map Reduce in Hadoop
One of the three components of Hadoop is Map Reduce. The first component of Hadoop that is, Hadoop Distributed File System (HDFS) is responsible for storing the file. The second component that is, Map Reduce is responsible for processing the file. MapReduce has mainly 2 tasks which are divided phase-wise.In first phase, Map is utilised and in next
9 min read
C# Multithreading
C# is a multi-paradigm programming language that supports several programming styles, including procedural, object-oriented, and functional programming. One of the essential features of C# is its support for multithreading, which enables developers to write applications that can perform multiple tasks concurrently. To create a new thread in C#, you
8 min read
Difference between Abstract Class and Interface in C#
An abstract class is a way to achieve abstraction in C#. To declare an abstract class, we use the abstract keyword. An Abstract class is never intended to be instantiated directly. This class must contain at least one abstract method, which is marked by the keyword or modifier abstract in the class definition. The Abstract classes are typically use
4 min read
C# | Arrays of Strings
An array is a collection of the same type variable. Whereas a string is a sequence of Unicode characters or array of characters. Therefore arrays of strings is an array of arrays of characters. Here, string array and arrays of strings both are same term. For Example, if you want to store the name of students of a class then you can use the arrays o
4 min read
Collections in C#
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } Collectio
5 min read
Introduction to .NET Framework
The .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The framework includes a variety of programming languages, such as C#, F#, and Visual Basic, and supports a range of application types,
7 min read
Common Language Runtime (CLR) in C#
The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others. When a C# program is compiled, the resulting executable code is in an intermediate
6 min read
Introduction to C# Windows Forms Applications
Windows Forms is a Graphical User Interface(GUI) class library which is bundled in .Net Framework. Its main purpose is to provide an easier interface to develop the applications for desktop, tablet, PCs. It is also termed as the WinForms. The applications which are developed by using Windows Forms or WinForms are known as the Windows Forms Applicat
4 min read
C# | List Class
List<T> class represents the list of objects which can be accessed by index. It comes under the System.Collections.Generic namespace. List class can be used to create a collection of different types like integers, strings etc. List<T> class also provides the methods to search, sort, and manipulate lists. Characteristics: It is different
6 min read
C# | Encapsulation
Encapsulation is defined as the wrapping up of data and information under a single unit. It is the mechanism that binds together the data and the functions that manipulate them. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield. Technically in encapsulation, the varia
5 min read
C# | Method Overriding
Method Overriding in C# is similar to the virtual function in C++. Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called as method overriding. In simple words, Overriding is a
8 min read
C# | How to check whether a List contains a specified element
List<T>.Contains(T) Method is used to check whether an element is in the List<T> or not. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot.List class can accept null as a valid value for reference types and it also allows duplicate elements.If the Count becomes equals to Capacity th
2 min read
C# | Count the total number of elements in the List
List class represents the list of objects which can be accessed by index. It comes under the System.Collection.Generic namespace. List class can be used to create a collection of different types like integers, strings etc. List class also provides the methods to search, sort, and manipulate lists. List.Count Property is used to get the total number
2 min read
C# | Delegates
A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered. For example, if you click on a Button on a form (Windows Form a
6 min read
C# | Inheritance
Introduction: Inheritance is a fundamental concept in object-oriented programming that allows us to define a new class based on an existing class. The new class inherits the properties and methods of the existing class and can also add new properties and methods of its own. Inheritance promotes code reuse, simplifies code maintenance, and improves
7 min read
C# | Generics - Introduction
Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces. A primary limitation of collections is the abs
6 min read
C# | Substring() Method
In C#, Substring() is a string method. It is used to retrieve a substring from the current instance of the string. This method can be overloaded by passing the different number of parameters to it as follows: String.Substring(Int32) Method String.Substring(Int32, Int32) Method String.Substring Method (startIndex) This method is used to retrieves a
3 min read
C# | Arrays
An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array specifies the number of elements present in the array
13 min read
C# | Constructors
A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor also contains the collection of instructions that are executed at the time of Object creation. It is used to assign initial values to the data members of the same class. Example : class Geek { ...
6 min read
C# | Data Types
Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C#, each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data type
7 min read
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)
Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These are used to cause the flow of execution to advance
5 min read
Article Tags :
three90RightbarBannerImg