What are the Best Ways to Declare Variables in C#

11 mins read

What are Variables In C#?

Variables are containers for storing data values. In C# we can say that a variable is a name given to a memory location and all the operations done on the variable effects that memory location. A variable is just a given name to a storage area that our programs can manipulate. Variables in C# have their specific types, which determine the size and layout of the variable’s memory the range of values that can be stored within that memory, and the set of operations that can be applied to the variable.

These are some examples of different types of variables in C#:

  • int – stores integers that are, whole numbers, positive or negative without decimals, such as 123 or -123. int  is short for “integer”, is a fundamental variable type built into the compiler and used to define numeric variables holding whole numbers.
  • double – stores floating-point numbers, with decimals, such as 19.99 or -19.99. The Double value type represents a double-precision 64-bit number with values ranging from negative 1.79769313486232e308 to positive 1.79769313486232e308, as well as positive or negative zero, PositiveInfinity, NegativeInfinity, and not a number (NaN). It is intended to represent values that are extremely large (such as distances between planets or galaxies) or minimal (such as the molecular mass of a substance in kilograms) and that often are imprecise (such as the distance from the earth to another solar system). The Double type complies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic.
  • char – stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotes. The char  type keyword is an alias for the .NET System. Char structure type that represents a Unicode UTF-16 character. The default value of the char  type is \0 , that is, U+0000. The char type supports comparison, equality, increment, and decrement operators. Moreover, for char operands, arithmetic and bitwise logical operators perform an operation on the corresponding character codes and produce the result of the int type. The char type store a character value from the range of +U0000 to U+FFFF
  • string – stores text, such as “Hello World”. String values are surrounded by double-quotes. A string is an object of the type String whose value is text. Internally, the text is stored as a sequential read-only collection of Char objects. There’s no null-terminating character at the end of a C# string; therefore, a C# string can contain any number of embedded null characters (‘\0’). The Length property of a string represents the number of char objects it contains, not the number of Unicode characters. To access the individual Unicode code points in a string, use the StringInfo object.
  • bool – stores values with two states: true  or false. The bool type keyword is an alias for the .NET System. Boolean structure type represents a Boolean value, which can be either true or false. To perform logical operations with values of the bool  type, use Boolean logical operators. The bool  type is the result type of comparison and equality operators. A bool expression can be a controlling conditional expression in the if, do, while, and forstatements and in the conditional operator?:. The default value of the bool  type is false.

How To Declare or Create Variables In C#

To create a variable, you must specify the type and assign it a value. Example:

Where type is a C# type (such as int or string), and variableName is the name of the variable (such as or name). The equal sign “=” is used to assign values to the variable. Now, we are going to create a variable that store text:

In the code sample above, we create a variable called name of type string and assign it the value “John”.

Output:

 

Now, let us create another variable that store a number:

In the code sample above, we declare a variable called myNum of type int and assign it the value 15.

Output:

We can also declare a variable without assigning the value, and assign the value later, like this:

The output will still be 15.

Note: If a new value is assigned to an existing variable, it will overwrite the previous value.

Code Sample:

Let us change the value of myNum to 20.

 

Ouput:

How Can I Use Constants In C#?

Constants are immutable values that are known at compile-time and do not change for the life of the program. Constants are declared with the const modifier. Only the C# built-in types (excluding System. Object) may be declared as const. User-defined types, including classes, structs, and arrays, cannot be const. Use the read only modifier to create a class, struct, or array that is initialized one time at run time (for example in a constructor) and thereafter cannot be changed.

Note: Constants must be initialized as they are declared.

You can add the const keyword if you don’t want others or yourself to overwrite existing values. This will declare the variable as “constant”, which means unchangeable and read-only.

Code Sample:

Output:

Why the error? Note that, you cannot declare a constant variable without assigning the value. If you do, an error will occur.

The const keyword is useful when you want a variable to always store the same value so that others or yourself won’t mess up your code. An example, that is often referred to as a constant, is PI (3.14159…).

How To Display Variables In C#

The WriteLine()  method is often used to display variable values to the console window.

Now, let us combine both text and a variable, we will use the +  character:

Output:

Note: You can also use the +  character to add a variable to another variable.

Code Sample:

Output:

For numeric values, the + character works as a mathematical operator. Let show code sample:

Notice that, we use int “integer” variables in the code sample above.

  • x stores the value 5
  • y stores the value 6
  • Then we use the WriteLine()  method to display the value of x + y, which is 11

Output:

How To Declare Many Variables In C#

To declare more than one variable of the same type, use a comma-separated list.

Code Sample:

Output:

 

You can also assign the same value to multiple variables in one line.

Code Sample:

Output:

What is C# Identifier?

An identifier is a name you assign to a type (class, interface, struct, record, delegate, or enum), member, variable, or namespace.

Identifiers Naming Rules:

Valid identifiers must follow these rules:

  • Identifiers must start with a letter or underscore ( _).
  • Identifiers may contain Unicode letter characters, decimal digit characters, Unicode connecting characters, Unicode combining characters, or Unicode formatting characters. You can declare identifiers that match C# keywords by using the @ prefix on the identifier. The @  is not part of the identifier name. For example, @if declares an identifier named if.

Identifiers Naming Conventions:

There are many identifiers naming conventions used throughout the .NET APIs. By convention, C# programs use PascalCase for type names, namespaces, and all public members. The following conventions are common:

  • Interface names start with a capital I.
  • Attribute types end with the word Attribute.
  • Enum types use a singular noun for non-flags and a plural noun for flags.
  • Identifiers shouldn’t contain two consecutive underscores ( _) characters. Those names are reserved for compiler-generated identifiers.

All C# variables must be identified with unique names. These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

Note: It is recommended to use descriptive names in order to create understandable and maintainable code.

Code Sample:

Output:

Thanks for reading…

Happy Coding!

Leave a Reply

Your email address will not be published.