C sharp (C#)

Constants in C#: Integer, Real, Character, Strings with examples

Constants in C#

As far as variable initialization is concerned, no difference from C/C++. A variable can be declared and initialized at the same time. A variable not yet initialized cannot be used, except to the left of an assignment. In other words: an uninitialized variable can be destination but cannot be a source in a transfer. There is thus no risk of misusing an uninitialized variable.

For example, we write:

int i=4;

int j, k=2; // only k is initialized

i = j; // compilation error

j = k; // correct

 

In what follows, we will consider the different types of C# constants (integer, real, etc.):


C# constants and #define directive:

While C# obviously allows you to represent C# constants, C# does not have the #define equivalent of C /C++ to represent constants (this practice is now discouraged in C++, for the benefit of const). #define certainly exists in C# but is used to define symbols that have a meaning for the programmer (they are defined or not, that’s all): we exclude or not from the compilation of parts of program. #undef has the opposite effect: the symbol is no longer defined. The #define and #undef directives should be placed at the very beginning of the program.

With

#define A

 

We tell the compiler that the symbol A exists. No particular value can be associated with the symbol (unlike C / C++).

Somewhere in the program, we can therefore find:

#if A

.....

#endif

 

The instructions represented by ….. will be taken into account here by the compiler (and therefore compiled and inserted into the executable program) since the symbol A was defined at the very beginning from the program. For these instructions to be taken into account by the compiler if the symbol B is not defined, we write:

# if! B

.....

#endif

 



Integer C# constants:

The only difference compared to C / C++: no octal representation in C#.

An integer value can be represented, as in C / C++:

  • in base 10, which is the case by default;
  • in base 16 (that is to say in hexadecimal representation), by prefixing the constant of 0x or 0X (number 0 followed by the letter X or x). Possible hexadecimal digits are digits from 0 to 9 as well as the letters from A to F (or from a to f, which is the same). 0x1BA4 therefore designates a value represented in the hexadecimal system (more precisely the value 7076 which corresponds to 1 * 212 + 11 * 28 + 10 * 24 + 4 * 20, i.e. 1 * 4096 + 11 * 256 + 10 * 16 + 4).

Any value starting with zero denotes a base 10 number (whereas in C / C++ it denotes a number in octal representation). 010 therefore designates the value ten. The octal representation, for the least incongruous on 8-bit multi-word machines (mainly now 32 and 64-bit), has therefore been discontinued, and no one will complain.

By default, integer C# constants are encoded on 32 bits, that is, in the format int. Those of which the value cannot be coded on 32 bits (for example ten billion) are however coded on 64 bits, that is, in the long format. Consider the following initializations (but beware, the third statement is in error):

int i1 = 100; No problem: 100 is well within an int.
int i2=0x64; Same thing: 0x64, that is 100, in i2.
short i3 = 100,000; Error: one hundred thousand does not fit within the limits of a pair of shorts!
short i4 = 100; No problem: 100 is within the limits of a pair of shorts.
long i5 = 10000000000; Ten billion is automatically encoded in the long format (therefore 64 bits) since it does not fit within the limits of an int.
int k = 5;

int i6 = k * 6;

 

i6 is initialized to the value 30.

int k = 5;

…..

k = a == 5? 100: 2;

…..

int i7 = k * 6;

 

 

if a is 5, k takes the value 100. Otherwise, k takes the value 2.

 

i7 is initialized to 600 if a contains 5. Otherwise, i7 is initialized to 12.



Long format suffix:

An integer C# constants can always be encoded in the long format as long as it is suffixed with the letter L (or its lowercase l, which should be avoided because of the confusion between the lowercase letter l and the number 1). C# constants 10 is therefore coded on 32 bits while constant 10L is coded on 64 bits (with zeros in the 32 most significant bits since the value is positive).

Calculation “errors”:

Appending or not the suffix L can have important consequences even if the compiler does not report any error. Consider the following instructions:

int i = 1,000,000,000; // a billion in i, no problem

long j;

j = i * 10; // wrong value in j!

i and 10 being both integers (more precisely int, which is the default format), the result of the calculation i * 10 is also encoded on an int (the compiler generates code so that so). At this point, the compiler doesn’t actually care what is to the left of the = sign. Since the value ten billion cannot be encoded in an int, it results (when executing the program) a calculation error. But nothing is reported to the user: the (erroneous) result of the operation is copied to j, which therefore does not contain ten billion.

Real C# constants:

Difference from C / C++: C# is more fussy. The real C# constants are, by default, encoded in double format, i.e. 64 bits. As in C / C++, a real constant can be expressed in normal or scientific form (with E or e to introduce the exponent, always a power of 10).

Possible real C# constants are (the second form being in error):

3.0 Normal form
3. Error: write 3 or 3.0.
0.3 Normal form
.3 Normal form (equivalent to the previous one)
3.1415 Normal form
1.2345E2 Scientific form (1.234 multiplied by 102, or 123.4)
123.4E-2 Scientific form (123.4 multiplied by 10-2, that is, 123.4 divided by 102, or 1.234).



The suffix f for floats:

A real C# constants can be encoded in a float representation that is to say on 32 bits, by suffixing it of f or F. We must therefore write (the second expression being incorrect):

double d = 1.2; No problem
float f1 = 1.2; Syntax error: 1.2 in double format.
float f2 = 1.2f; No problem
float f3 = (float)1.2; Also accepted
float f4 = 1.2e10f; Scientific form and float format.

Now let’s analyze the following instructions to explain the error on the second instruction:

short s=10; is correct: all integer values ​​are represented exactly and the value 10 enters well in the field of shorts. There is therefore no loss of information when copying the value 10 (by default encoded on 32 bits) in a short.
float f=1.2; is incorrect: the value 1.2 is represented in double format, that is to say with more precision

than in float. There would therefore be a loss of information when copying the value 1.2 into f. In performing the casting, we signal to the compiler that we accept the loss of precision. So it was necessary to write :

float f = 1.2f;

or

float f = (float) 1.2;

double d = 1.2f; is correct: no loss of information when switching from float to double since double is more precise than float.

Nothing prevents suffixing a real constant of d or D to specify a double format (even if a constant is encoded in this format by default, which makes the suffix unnecessary).

The m suffix for the decimal type:

A real C# constants can be encoded in a decimal representation (therefore with exactitude) by suffixing it of m or M.

decimal d1 = 1.2m;

double d2 = (double) d1;



Character C# constants:

A C# constants of type char contains a 16-bit number. Usually this is the code a letter (the one with this value in the Unicode table). A constant of type char can be represented in different ways:

char c1 = ‘A’; Letter A (in Unicode representation) in c1.
char c2 = ‘\x41’; Letter corresponding to the value 0x41 (65 in decimal) in Unicode. A is therefore copied into c2 (we find the ANSI code at the very beginning of Unicode).
char c3 = (char) 65; Same thing.
char c4 = ‘\u0041’; Unicode value 41 (in hexadecimal) in c4. The value must be coded on four digits hexadecimal.

Note that a letter is surrounded by ’(single quote). For the tank to contain this character, it suffices to describe :

char c = ‘\’ ‘;

Do not confuse “A” (letter A) with “A” (character string consisting of the single letter A). In computer science, these are two very different things.

Character Strings C# constants:

A C# constants of type “character string” can be represented as in C / C++ (without forgetting that each character is encoded on 16 bits, even if this remains relatively transparent for the programmer):

string s = “Hello”;

A constant of type char is usually expressed as a character inserted between ’. Some control characters can be inserted between single quote:

char c = ‘\ n’;

but also in a character string surrounded by double quotes:

string s = “ABC \ nDEF”;

These control characters are:

Denomination English term Representation Value
At the line newline \n 0x000A
Horizontal tab horizontal tab \t 0x0009
Vertical tab vertical tab \v 0x000B
Going back backspace \b 0x0008
Carriage return carriage return

form feed

\r

\f

0x000D

0x000C

Backslash backslash \\ 0x005C
Single quote single quote \’ 0x0027
Double quote double quotes \” 0x0022
Null value character null \0 0

As in C / C++, remember to repeat the character \ in a string. Otherwise the compiler assumes that \ introduces a control character, such as \ n. Another technique, to avoid having to repeating the \, consists of prefixing the string of @ (we speak of a verbatim string). This technique is widely used to specify a file name with directory (for example @ “C: \ Dir1 \ Dir2 \ Fich.dat”, which is equivalent to “C: \\ Dir1 \\ Dir2 \\ Datasheet”).

There is however an exception to this rule: we insert a “(quote) in a verbatim string by repeating the “. So, to copy AA” BB (with a double quote between the two A’s and the two B’s) in s, we writes:

string s = @ “AA” “BB”;    // or “AA \” BB “

To copy “Hello” (with a double quote at the beginning and another at the end):

s = @ “” “Hello” “”;     // or “\” Hello \ “”

Let’s analyze some examples:

Instructions Display
string s1 = “123  \ nABC”;

Console.WriteLine (s1);

123

ABC

string s2 = “123 \\ nABC”;

Console.WriteLine (s2);

123\nABC

 

string s3 = @ “123 \ nABC”;

Console.WriteLine (s3);

123\nABC

In the second example (with s2), we find \\ n. The compiler detects \\ (which means that we inserts a backslash) followed by n.

The compiler reports an error if you write:

string s = “AAA

BBB

CCC “;

But we can write:

string s = @ “AAA

BBB

CCC “;

and the compiler inserts a line break after AAA and BBB.

WriteLine (function of the Console class in the System namespace) always causes a line break after the display. Write is used like WriteLine but does not perform a jump line after each display.

On Windows, a carriage return must be specified by the sequence \ r \ n, while on Unix, it it’s just the \ n. A technique for remaining independent of the platform (or not having to deal with these issues) is to specify Environment.NewLine:

string s = “AA” + Environment.NewLine + “BB”;



Programming Examples:

How to use Character String Constant:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Fawad\tKhan\nOwner of\nProgramming Digest");
            Console.ReadLine();
        }
    }
}

constants in C#


How to define and use C# constant in programming:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            const double pi = 3.14159;

            // constant declaration 
            double r;
            Console.WriteLine("Enter Radius: ");
            r = Convert.ToDouble(Console.ReadLine());

            double areaCircle = pi * r * r;
            Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
            Console.ReadLine();
        }
    }
}

constants in C#

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button