Literals in C#

Literals or Constants in C# with Examples

In this article, I am going to discuss Literals or Constants in C# with Examples. Please read our previous article, where we discussed Data Types in C# with Examples. At the end of this article, you will understand what are literals and when and how to use Literals in C# Applications.

Literals or Constants in C#

The Literals in C# are the fixed values and these fixed values are used by Variables and the values cannot be modified during the execution of the program.

  1. The fixed values are called Literals in C#.
  2. Literal is a value that is used by the variables. 

These are the convenient form of constant values like other variables but constants refer to fixed values that cannot be changed during the execution of the program. These fixed values are also called literals in C#. The constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, a string literal constant, or an enumeration constant.

Note: The constants or literals are treated just like regular variables except that their values cannot be modified after their declaration. Literals and Constants are the same.

Types of Literals or Constants in C#

There are different types of literal available in C#. There as follows.

  1. Integer Literals
  2. String Literals
  3. Character Literals
  4. Floating-point Literals
  5. Boolean Literals

Let us discuss each of these Literals in C# with Examples.

Integer Literals in C#:

A literal of integer type is known as the integer literal. The literal of integer type can be octal, decimal, binary, or hexadecimal constant. The prefix is used to specify whether it is decimal, octal, or hexadecimal. 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. The integer literal can be specified in four ways:

  1. Decimal (Base-10): Digits from 0-9 are allowed in this form. No prefix is required for the decimal type of literal. Example: int x=101;
  2. Octal (Base-8): Digits from 0 – 7 are allowed. The octal number should always have a prefix 0. Example: int x=0146;
  3. Hexa-Decimal (Base-16): Digits 0-9 are allowed and also characters from a-f are allowed in this form. Furthermore, both uppercase and lowercase characters can be used. C# provides an exception here i.e. As we know that C# is a case-sensitive programming language but here C# is not case-sensitive. Example: int x = 0X123Face;
  4. Binary: In this form, the allowed digits are only 1’s and 0’s. The binary number should be prefixed with 0b. Example: int x = 0b1111;
Example to Understand Integer Literals in C# Language
using System;
namespace LiteralsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 101; // decimal literal 
            int b = 0146; // octal literal 
            int c = 0x123Face; // Hexa-decimal literal 
            int d = 0b1111; // Binary literal 

            Console.WriteLine("Decimal Literal : " + a);
            Console.WriteLine("Octal Literal : " + b);
            Console.WriteLine("Hexa-Decimal Literal : " + c);
            Console.WriteLine("Binary Literal : " + d);

            Console.ReadKey();
        }
    }
}
Output:

Example to Understand Integer Literals in C# Language

Floating-Point Literals in C#:

The Literals in C# which have an integer part, a decimal point, a fractional part, and an exponent part are known as the floating-point literals. These can be represented either in decimal form or in exponential form. That means the Floating-point literals represent decimal values with a fractional component. For Floating-point data types, we can specify literals in only decimal form and we can’t specify in Octal and Hexadecimal forms. The floating type literal is of double type. F or f can be used as a suffix to specify the value as it cannot be assigned directly to the float variable.

Example to Understand Floating-point Literals in C#:
using System;
namespace LiteralsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            double a = 3.1231;      // Valid
            double b = 123469E-5;   // Valid
           // double c = 125E;      // invalid: Incomplete exponent 
            double d = 784f;        // valid
           // double e = .e45;      // invalid: missing integer or fraction

            Console.WriteLine(a);
            Console.WriteLine(b);
            Console.WriteLine(d);
            Console.ReadKey();
        }
    }
}
Output:

Example to Understand Floating-point Literals in C#

Note: By default, every floating-point literal is of double type and hence we can’t assign directly to float type variables. 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 in C#:

The Character Literals in C# are enclosed in single quotes, for example, ‘a’, and can be stored in a simple variable of char data type. A character literal can be a plain character for example, ‘a’, an escape sequence for example, ‘ \t’, or a universal character for example, ‘\u02B0’. So, for character data types we can specify character literals in 3 ways:

1. Single Quote:

We can specify Character literals to a char data type as a single character using a single quote.

char ch = ‘a’;

2. Unicode Representation:

We can specify Character literals using Unicode representation ‘\uxxxx’ where xxxx are the hexadecimal numbers.

char ch = ‘\u0061’; // Here /u0061 represent a.

3. Escape Sequence:

Every escape character can be specified as char literal. There are some escape characters known as char literals.

char ch = ‘\n’;

Example to Understand Character Literals in C#:
using System;
namespace LiteralsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //character literal within single quote
            char ch1 = 'a';
            Console.WriteLine("Single Quote: " + ch1);

            //character literal using Unicode representation
            char ch2 = '\u0061';
            Console.WriteLine("Unicode: " + ch2);

            // Escape character literal
            Console.WriteLine("Escape: Hello\n\nDotNetTutorials\t!");

            Console.ReadKey();
        }
    }
}
Output:

Example to Understand Character Literals in C#

Note: There are certain characters in C# when preceded by a backslash, which will have a special meaning that they are used to represent. For example, newline (\n) and tab (\t). The following is the list of some of the escape sequence codes available in C#:

Literals in C#

String Literals in C#:

The Literals in C# which are enclosed with double quotes (“”) or start with @”” are known as the String literals or String Constants. Long lines can be broken into multiple lines with string literals and separated by using blank spaces. A string contains characters that are similar to character literals i.e. string literals can contain plain characters, escape sequences, and universal characters.

Example:
String str1 = “Dot Net Tutorials”;
String str2 = @”Dot Net Tutorials”;

Example to understand String Literals in C#:
using System;
namespace LiteralsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            String str1 = "Dot Net Tutorials";
            String str2 = @"Dot Net Tutorials";

            Console.WriteLine(str1);
            Console.WriteLine(str2);

            Console.ReadKey();
        }
    }
}
Output:

Example to understand String Literals in C#

Boolean Literals in C#:

Only two values are allowed for Boolean literals i.e. true and false. Boolean literals are simple. There are only two logical values that a boolean value can have, true and false. The values of true and false do not convert into any numerical representation. The true literal in C# does not equal 1, nor does the false literal equal 0.

Example:
bool a = true;
bool b = false;

Example to understand Boolean Literals in C#:
using System;
namespace LiteralsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            bool a = true;
            bool b = false;
            // bool c = 0; //error
            // bool d = 1; //error 

            Console.WriteLine(a);
            Console.WriteLine(b);

            Console.ReadKey();
        }
    }
}
Binary Literals in C#:

In C# 7.0 Binary Literals are introduced. The binary literal is used to store the binary value in a variable. And the binary literal is represented by 0b. Binary literals are mainly used for bitmasks.

Example: var num = 0b10001

Here when the compiler sees 0b in the variable value, then it automatically treated this num as a binary literal. If you try to run this on the compilers below C# 7.0, then the compiler will throw an error because this feature is introduced in C# 7.0 so, it will only work on C# 7.0 and above compilers.

Example to understand Binary Literals:
using System;
namespace LiteralsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating binary literals by prefixing with 0b
            var num1 = 0b1001;
            var num2 = 0b01000011;

            Console.WriteLine("Value of Num1 is: " + num1);
            Console.WriteLine("Value of Num2 is: " + num2);
            Console.WriteLine("Char value of Num2 is: {0}",Convert.ToChar(num2));

            Console.ReadKey();
        }
    }
}
Output:

Example to understand Binary Literals in C#

Note: C# Binary Literals feature allows us to deal with binary values in the C# application. By using this feature, we can store binary values in variables. C# provides 0b literals to create binary values. C# compiler recognizes these literals and treats values accordingly.

In the next article, I am going to discuss Type Casting in C# with Examples. Here, in this article, I try to explain Literals or Constants in C# with Examples. I hope you enjoy this article.

Leave a Reply

Your email address will not be published.