find and solve || findandsolve.com
Please wait.....

C# Variables: Declare, Access & Use

Containers for storing data values are Variables. The different types of variables are as follows:

  •  int- it stores the integers (whole numbers) without decimals. Ex. 245, -678
  •  double- it stores the floating point numbers, with decimals. For ex. 18.25 or -18.25. Upto 15 digit decimal point will be executed.
  •  char- stores single characters, such as ‘b’ or ‘C’. However, it can also be surrounded by double quotes.
  •  string – it usually stores text, such as “ Hello World”. These values are surrounded by double quotes.
  •  bool- values are stored with two states either true(1) or false(0).


Declaring or Creating Variables

To create a variable, its type should be specified and value should be assigned.

Syntax: type variableName = value;

where type is C# type( such as int or string), and variableName is name of variable( such as b or name). Equal sign is used to assign values to the variable.

Example
string name = “FindAndSolve”;

Console.WriteLine(name);

output

FindAndSolve


Constants

 The const keyword is useful for always storing same value, so our code won’t get messed up. Example: PI(3.1415…).

const int myNum = 124;

myNum = 1347; // error

Note: A constant variable cannot be declared without assigning a value. Otherwise, an error will occur.

Display Variables

WriteLine() method is used to display values of variable to console window. To combine both text and variable, + character should be used.

Example
string name = "FindAndSolve";

Console.WriteLine("Hello " + name);
output

Hello FindAndSolve

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

Example
string firstName = "FindAndSolve";
string lastName = "Online Tutorial";
string fullName = firstName + lastName;
Console.WriteLine(fullName);
output

FindAndSolve Online Tutorial


For numeric values, the + character works as a mathematical operator (notice that we use int (integer) variables here):

Example
int x = 10;

int y = 7;
Console.WriteLine(x + y); // Print the value of x + y
output

17

From the example above, you can expect:

  • x stores the value 10
  •  y stores the value 7
  •  Then we use the WriteLine() method to display the value of x + y, which is 17.


Declaring Many Variables

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

Example
int x = 7, y = 8, z = 15;

Console.WriteLine(x + y + z);
output

30


C# Identifiers

All C# variables must be identified with unique names called identifiers. It can be short names ( a and b) or more descriptive names( age, sum, totalVolume).

Note: To create the code which is understand and maintained, it is recommended to use descriptive names.

Example
// Good
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is int m = 60;
General rules for naming variables:
  • Names contain digits, letters, underscore character(_)
  • Must begin with a letter.
  • Should start with a lowercase letter and cannot contain whitespace.
  • These are case sensitive(“myVar” and “myvar” are different variables)
  • Reserved words ( like C# keywords, such as int or double) can’t be used as names.



A variable in C# is a container to store a value of a specific type, such as int, string, double, etc. Variables can be declared using the syntax <type> <variable_name>, and values can be assigned using =. Examples:

C#
int age = 30; string name = "John"; double pi = 3.14;

Scope of variables in C#

In C#, the scope of a variable determines where in the code the variable can be accessed and used. There are two types of scope in C#:

  1. Local scope: Variables declared inside a method or block have a local scope and can only be accessed within that method or block. Once the method or block is exited, the variable is destroyed and its value is lost.

Example:

csharp
void MethodA() { int x = 10; Console.WriteLine(x); // outputs 10 } Console.WriteLine(x); // Error: x is not defined
  1. Global scope: Variables declared outside any method or block have a global scope and can be accessed from anywhere in the code.

Example:

csharp
int y = 20; void MethodB() { Console.WriteLine(y); // outputs 20 } Console.WriteLine(y); // outputs 20

It's also possible to have variables with the same name but with different scopes, as long as they are in different blocks or methods. In this case, the most local scope will take precedence over a wider scope.


How to use int in c#

In C#, int is a data type that represents a 32-bit signed integer. You can use an int variable to store whole numbers (integers) within a certain range, e.g.:

python
int num = 42;

You can perform various operations on int values, such as arithmetic operations (e.g. addition, subtraction, multiplication, division) and comparison operations (e.g. equality, less than, greater than).

For example:

C#
int num1 = 10; int num2 = 20; int result = num1 + num2; Console.WriteLine(result); // Output: 30

How to use double in c#

In C#, double is a data type that represents a 64-bit floating-point number. You can use a double variable to store decimal numbers with a high degree of precision, e.g.:

C#
double d = 3.14;

You can perform various operations on double values, such as arithmetic operations (e.g. addition, subtraction, multiplication, division) and comparison operations (e.g. equality, less than, greater than).

For example:

scss
double d1 = 1.23; double d2 = 4.56; double result = d1 + d2; Console.WriteLine(result); // Output: 5.79

Note that you can use the f or F suffix to specify a float literal in C#, which is a single-precision floating-point number that occupies less memory than a double.


How to use char in c#

In C#, char is a data type that represents a single Unicode character, e.g.:

C#
char c = 'A';

You can use a char variable to store a single character or symbol, such as a letter, digit, punctuation mark, or whitespace. A char value must be enclosed in single quotes (').

For example:

java
char ch = 'x'; Console.WriteLine(ch); // Output: x

You can perform various operations on char values, such as comparing two characters for equality or ordering them in a certain way. You can also convert a char value to its corresponding numeric representation (its Unicode code point) using the (int) cast operator.

For example:


char ch1 = 'A'; char ch2 = 'B'; bool result = ch1 < ch2; Console.WriteLine(result); // Output: True


How to use string in c#

In C#, string is a data type that represents a sequence of Unicode characters. You can use a string variable to store one or more characters, such as a word, sentence, or paragraph, e.g.:


string s = "Hello, World!";

A string value must be enclosed in double quotes ("). You can concatenate two or more strings using the + operator, or use string interpolation to embed expressions within a string.

For example:


string name = "John"; string greeting = "Hello, " + name + "!"; Console.WriteLine(greeting); // Output: Hello, John!
csharp
string name = "John"; int age = 30; string info = $"Name: {name}, Age: {age}"; Console.WriteLine(info); // Output: Name: John, Age: 30

You can also perform various operations on string values, such as finding the length of a string, extracting a substring, or comparing two strings for equality or ordering.

For example:

java
string s1 = "Hello"; string s2 = "World"; bool result = s1 == s2; Console.WriteLine(result); // Output: False


How to use bool in c#

In C#, bool is a data type that represents a Boolean value, which can be either true or false. You can use a bool variable to store a binary decision, such as a test for equality or a condition for a control flow statement, e.g.:

C#
bool b = true;

You can perform various operations on bool values, such as negating a value using the ! operator or combining two values using the logical && (and) or || (or) operators.

For example:


bool condition1 = 5 > 3; bool condition2 = 2 < 1; bool result = condition1 && condition2; Console.WriteLine(result); // Output: False

bool condition1 = 5 > 3; bool condition2 = 2 < 1; bool result = condition1 || condition2; Console.WriteLine(result); // Output: True


Related information