csharp

Variables in C# with Programming Examples

Variables in c#:

Variables in c#:- As mentioned earlier, the variables are related to data storage. In fact, you can think of variables in your computer’s memory as boxes on the shelf. You can put things in boxes and take them out again, or you can just look inside the box to see if there is anything there. It’s the same with variables; you put data in it and can take it out or view it if necessary.

Although all the data in the computer is actually the same (a sequence of zeros and ones), variables In c# come in different kinds, known as types. If you use the analogy with boxes again, the boxes come in different shapes and sizes, so some items are placed only in certain boxes. The rationale behind this type of system is that different types of data may require different manipulation methods, and by limiting variables to individual types, you can avoid mixing them. For example, it doesn’t make sense to treat the sequence of zeros and ones that make up a digital image as an audio file.

To use variables in c#, you have to declare them. This means that you have to give them a name and type. Once you’ve declared the variables in c#, you can use them as storage units for the type of data you’ve declared for storing them. Syntax  of C# to declare variables simply indicates the type and name of the variable:

< type > < name > ;

If you try to use a variable in c# that hasn’t been declared, your code won’t be compiled, but in this case the compiler will tell you exactly what the problem is, so it’s not really a catastrophic error. Trying to use a variable without assigning a value to it also causes an error, but again, the compiler detects it. You can use an almost infinite number of types. This is because you can identify your own types to store any confusing data that you like. However, there are certain types of data that almost everyone will need to use at some point, such as the c# variable in which the number is stored. Therefore, you should be aware of a few simple predetermined types.



Simple Types of variables in c#

Simple types include types such as numbers and logical (true or false) values that make up the fundamental building blocks for your applications. Unlike there are no children or attributes of simple types like complex types. Most of the available simple types are numerical, which at first glance seems a little strange – after all, to store the number only one type?

The reason for the abundance of numerical types lies in the mechanism of storing numbers in the computer’s memory in the form of a sequence of zeros and units. For integer values, you simply take a number of bits (separate numbers that can be 0 or 1) and present your number in a binary format. The variable, which stores N bits, allows you to represent any number from 0 to (2 N – 1). Any numbers above this value are too high for this variable. For example, let’s say you have a variable that can store 2 bits. Thus, the correspondence between the whole numbers and bits representing these numbers is as follows:

0 = 00

1 = 01

2 = 10

3 = 11

If you want to be able to store more numbers, you need more bits (for example, 3 bits allow you to store numbers from 0 to 7).

The inevitable result of this system is that you will need an infinite number of bits to be able to store all imaginable numbers that will not fit in your reliable PC. Even if you could use a certain number of bits for each number, of course, it would be inefficient to use all these bits for a variable that, for example, had to store only numbers from 0 to 10 (because storage was wasted). Four bits are great here, allowing you to store a lot more values in that range in the same memory space.

Instead, you can use a number of different integers to store different ranges of numbers that take up different memory amounts (up to 64 bits). These types are shown in the following table.

Type Alias For Allowed Values
sbyte System.SByte Integer between – 128 and 127
byte System.Byte Integer between 0 and 255
short System.Int16 Integer between – 32768 and 32767
ushort System.UInt16 Integer between 0 and 65535
int System.Int32 Integer between – 2147483648 and 2147483647
uint System.UInt32 Integer between 0 and 4294967295
long System.Int64 Integer between – 9223372036854775808 and

9223372036854775807

ulong System.UInt64 Integer between 0 and 18446744073709551615

U symbols in front of some variable names are short for unsigned, which means you can’t store negative numbers in these types of variables in c#, as shown in the Table Acceptable Values column.

Of course, you also need to store floating comma values that are not whole numbers. You can use three types of floating comma variables: float, double, and decimal. The first two store numbers with a floating comma in the form of q / – m × 2e, where the allowable values for m and e vary for each type. × These three types are shown in the following table along with their valid m and e values and these limitations in real numerical terms:

Type Alias

For

Min M Max M Min E Max E Approx. Min Value Approx. Max Value
float System.Single 0 224 -149 104 1.5 x1045 3.4 x1038
double System.Double 0 253 -1075 970 5.0 x 10-324 1.7 x10308
decimal System.Decimal 0 296 -26 0 1.0 x 10-28 7.9 x1028

In addition to numerical types, there are three simple types available:

Type Alias For Accepted Values
char System.Char Single Unicode character, stored as an integer between 0 and 65535
bool System.Boolean Boolean value, true or false
string System.String A sequence of characters

Note that there is no upper limit on the number of characters that make up the line because it can use different amounts of memory.

The logical type of bool is one of the most commonly used types of variables in C#, and indeed, similar types are equally common in code in other languages. Having a variable that can be true or false has important branches when it comes to logic in an application. As a simple example, let’s look at how many questions can be answered “true” or “false” (yes and no). Comparing variable values or checking input are just two of the software applications of logical variables in c# that you’ll learn in my upcoming articles.

Now that you’ve become familiar with these types, let’s look at a small example of their ad and use. In the next exercise, you use a simple code that declares two variables, assigns them values, and then displays those values.


Example how to use Using Simple Type Variables in c#:

Output:

variables in c#

code Explanation:

The added code has three functions:

  • It declares two variables.
  • It assigns values to those two variables.
  • These two variables in c# show the values on the console

The declares of the variable takes place in the following code:

int intVal;

string stingVal;

The first line declares an int type variable with the name intval, and the second line declares a string type variable named stringVal.

The following two lines of code assign values:

intVal = 200;

stringVal =”\” intVal ” is”;

Here, you assign two fixed values (known as literal values in the code) to the  with the assigning statement. You assign an integer value of 200 intVal, and the line “intVal” (including quotes) – stringVal. When you assign string values in this way, double quotes are required to conclude a line. Therefore, some characters can cause problems if they are included in the line itself, such as double quotes, and you have to screen some characters by substituting a sequence of characters (escape-sequence) that represents the character (characters) that you want to use. In this example, you’re using a sequence of ‘\’ to avoid double quotes:

stringVal = “\”intVal\” is”;

If you haven’t used these escape sequences and tried to code this as

stringVal = “”intVal” is”;

you’ll get a compiler error.

Note that assigning string literals is another situation in which you have to be careful with line transfers – the compiler C# is rejecting string literals covering more than one line. If you want to add a line break, use the escape sequence to return the carriage in your which is \n, i.e. n. For example, a job

stringval = “This string has a\nline break.”;

show up in two lines in the console view as follows:

This string has a

line break.

All escape sequences consist of a reverse oblique symbol, followed by one of a small set of characters (the full set you’ll see later). Since this symbol is used for this purpose, there is also an escape sequence for the backlash symbol itself, which is just two consecutive backslashes ( \). Going back to the code, there’s another new line to look out for:

Console.WriteLine(“{0} {1}.”, stringval, intVal);

This is similar to a simple method of typing into a console that you saw in the first example, but now you specify your variables. In order not to get ahead of ourselves, we will not go into the details of this line of code. Suffice it to say that this is a method that you will use in the first part of this book to display text in the console window. There are two things in brackets:

  • A string
  • A list of variables in c# that you want to insert into the output line separated by commas.

The line you’re displaying, “{0} {1}.,” doesn’t seem to contain a lot of useful text. However, as has been shown before, this is not what you actually see when you run the code. That’s because the line is actually the template in which you insert the contents of your variables. Each set of curly brackets in a row is a placeholder that will contain the contents of one of the variables in the list.

Each placeholder (or format string line) is presented as a whole number, enclosed in curly braces. Entire numbers start at 0 and increase by 1, and the total number of placeholders should correspond to the number of variables listed in the comma-divided list after the line. When the text is displayed on the console, each placeholder is replaced by the appropriate value for each variable. In the previous example, {0} is replaced by the actual value of the first stringVal variable, and {1} is replaced by intVal content. This method of typing on a console is what you use to display your code output in the following examples. Finally, the code has a line shown in the previous example to wait for the user to enter before it ends:

Console.ReadKey();

Again, the code is not being analyzed now, but you’ll often see it in later examples. In the meantime, keep in mind that the code is suspended until you hit the key.


Naming variables in c#

As mentioned in the previous section, you can’t just choose any character sequence as a variable name. However, this is not as alarming as it may seem at first glance because you still have a very flexible naming system.

The basic rules for naming variables in c# are as follows:

  • The first symbol of the variable name should be a letter, an underlining symbol, or a symbol ( @).
  • Subsequent symbols can be letters, underline symbols, or numbers.

There are also certain keywords that have a special meaning for the C# compiler, such as the use keywords and namespace that were shown earlier. If you use one of these by mistake, the compiler will complain, so don’t worry about it.

For example, you can use the following variable names:

myBigVar

VAR1

_test

These are not, however:

99BottlesOfBeer

namespace

It’s-All-Over

Keep in mind that the C# is sensitive to the register, so be careful not to forget the exact register used when declaring variables in c#. References to them made later in the program, even with one letter in the wrong register, prevent compilation. Another consequence of this is that you may have several variables in c# whose names differ only in the register. For example, these are all individual names:

myVariable

MyVariable

MYVARIABLE

Variables Naming Conventions in C#

You’ll often use variable names, so it’s worth spending a little time learning which names to use. However, before you start, keep in mind that this is a moot point. Over the years, different systems have come and gone, and many developers will struggle to justify their personal system.

Until recently, the most popular system was the so-called Hungarian notation. This system includes adding a prefix in the lower register to all the names of variables that identify the type. For example, if a variable has an int type, you can place i (or n) in front of it, such as iAge. Using this system, it is easy to see the type of variable at first sight.

However, more modern languages, such as C#, make it more difficult to implement this system. For the types that you’ve seen so far, you could probably come up with one- or two-letter prefixes denoting each type. However, since you can create your own types, and the base .NET Framework has hundreds of these more complex types, it quickly becomes unworkable. When several people work on a project, different people can easily come up with different and confusing prefixes, which can be disastrous.

The developers realized that it is much better to name variables in c# that correspond to their goals. If there are any doubts, it is easy enough to determine the type of variable. In VS and VCE, you just need to pointer the mouse in the name of the variable, and the pop-up will tell you which type is soon enough. There are currently two name agreements in the .NET Framework: PascalCase and camelCase. The register used in the names indicates their use. Both apply to multi-word names, and both determine that each word in the name should be in the lower register, except for its first letter, which should be in the upper register. For camelCase terms, there is an additional rule: the first word must start with a lowercase letter.

Below are the names of the camelCase variables:The following are camelCase variable names:

age

firstName

timeOfDeath

These are PascalCase:

Age

LastName

WinterOfDiscontent

Use camelCase for simple variables in c#. Use PascalCase for some more complex names, which is Microsoft’s recommendation. Finally, note that many past naming systems have often used an underlining symbol, usually as a divider between words in variable names, such as still_another_variable. Such use is not recommended now (which is also good; it looks ugly!).



Literal Values:

the whole number and the string and Other types of variables also have associated literal values, as shown in the following table. Many of these include suffixes, through which you add a sequence of characters to the end of the literal value to indicate the desired type. Some literals have several types defined by the compiler during compilation, depending on their context (also shown in the table).

Type Category Suffix Example
bool Boolean None true or false
int , uint , long ,ulong Integer None 100
uint , ulong Integer u or U 100U
long , ulong Integer l or L 100L
Ulong Integer ul , uL , Ul , UL , lu , lU ,Lu , or LU 100UL
Float Real f or F 1.5F
Double Real None, d , or D 1.5
Decimal Real m or M 1.5M
Char Character None ‘a’ , or escape sequence
String String None “ a…a ” , may include escape sequences

String Literals

Earlier in this article, you’ve seen several escape sequences that you can use in string literals. Here’s their full table for reference:

Escape Sequence Character Produced Unicode Value of Character
\’ Single quotation mark 0x0027
\ “ Double quotation mark 0x0022
\\ Backslash 0x005C
\0 Null 0x0000
\a Alert (causes a beep) 0x0007
\b Backspace 0x0008
\f Form feed 0x000C
\n New line 0x000A
\r Carriage return 0x000D
\t Horizontal tab 0x0009
\v Vertical tab 0x000B

 

The Unicode Value column in the previous table shows the hexadecimal values of the characters as they are in the Unicode character set. Like the previous one, you can specify any Unicode symbol using the Unicode escape sequence. They consist of a standard symbol, followed by u and a four-digit hexadecimal value (e.g. four digits after x in the previous table).

This means that the following lines are equivalent to:

“programming\’s string.”

“Digest\u0027s string.”

Obviously, you have more opportunities to use The Unicode escape sequences.

You can also specify the lines verbatim. This means that all characters between the two double quotes are included in the line, including the end of the line and the symbols that would otherwise need to be screened. The only exception to this rule is the escape sequence for the double quote symbol, which must be specified to avoid the end of the line. To do this, place the symbol in front of the line:

@”Verbatim string literal.”

This line can also be easily specified in the usual way, but the following method requires:

@”A short list:

item 1

item 2”

Verbatim strings are particularly useful in file names because they use many reverse oblique characters. When using regular lines, you’ll have to use a double reverse slash across the line:

“C:\Temp\MyDir\MyFile.doc”

With verbatim string literal literals, you can make it more readable. The following literal line is equivalent to the previous one:

@”C:\Temp\MyDir\MyFile.doc”


Variables Declaration and Assignment in c#

Recall that you declare variables simply by using their type and name:

int age;

You then assign values to variables with the assigning statement:

Age: 25;

Keep in mind that variables in c# need to be initiated before they are used. The previous assignment can be used as an initialization. Here you can do a few more things that you’ll probably see in the code C#. First, you can declare several variables of the same type at the same time by dividing their names into commas after type, as shown here:

int xSize, ySize;

Here xSize and ySize are declared as integer types.

The second method you’ll probably see is that values are assigned to variables when they are declared, which basically means combining two lines of code:

int age = 25;

You can use both of these methods together:

int xSize = 4, ySize = 5;

Here the different values are assigned to xSize and ySize. Note that

int xSize, ySize = 5;

results in the initialization of only ySize – xSize have just been declared, and it still needs to be initiated before use.


Related Article:

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

Data types in C#: integer, Boolean, Real, Char and String with examples

Related Articles

Leave a Reply

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

Back to top button