Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • C# - Get Started
  • C# - Version History
  • C# - First Program
  • C# - Keywords
  • C# - Class and Objects
  • C# - Namespace
  • C# - Variables
  • C# - Implicitly-Typed Variables
  • C# - Data Types
  • Numbers
  • Strings
  • DateTime
  • Structure
  • Enum
  • StringBuilder
  • Anonymous Types
  • Dynamic Types
  • Nullable Types
  • C# - Value & Reference Types
  • C# - Interface
  • C# - Operators
  • C# - if else Statements
  • C# - Ternary Operator ?:
  • C# - Switch
  • C# - For Loop
  • C# - While Loop
  • C# - Do-while Loop
  • C# - Partial Class
  • C# - Static
  • C# - Array
  • Multidimensional Array
  • Jagged Array
  • C# - Indexer
  • C# - Generics
  • Generic Constraints
  • C# - Collections
  • ArrayList
  • List
  • SortedList
  • Dictionary
  • Hashtable
  • Stack
  • Queue
  • C# - Tuple
  • C# - ValueTuple
  • C# - Built-in Exceptions
  • Exception Handling
  • throw
  • Custom Exception
  • C# - Delegates
  • Func Delegate
  • Action Delegate
  • Predicate Delegate
  • Anonymous Methods
  • C# - Events
  • C# - Covariance
  • C# - Extension Method
  • C# - Stream I/O
  • C# - File
  • C# - FileInfo
  • C# - Object Initializer
  • OOP - Overview
  • Object-Oriented Programming
  • Abstraction
  • Encapsulation
  • Association & Composition
  • Inheritance
  • Polymorphism
  • Method Overriding
  • Method Hiding
  • C# - Solid Principles
  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle
  • Design Patterns
  • Singleton
  • Abstract Factory
  • Factory Method
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

C# Variables

Variables in C# are the same as variables in mathematics. Before we understand what is a variable, let's understand the expressions. The followings are examples of expressions.

Example: Expressions
10 + 20
5 * 2
10/2

The result of the above expressions are fixed e.g. 10 + 20 = 30, 5 * 2 = 10 and 10/2 = 5. Now, consider the following expressions.

Example: Expressions with Variable
x + 20
y * 2
z/2

The result of the above expression depends on the value of x, y and z. For example, if x = 5 then the result of x + 20 would be 25 and if x = 20 then the result of x + 20 would be 40. In the same way, the result of y * 2 depends on the value of y and the result of z/2 depends on the value of z. Here, x, y, z are called variables because their values can be changed.

The same concept is used in C#. In C#, a variable stores a value of the specific data type. It can store a numeric, char, string, or other types of value. You can declare and assign a value to a variable like int x = 5; where int is the data type, x is the name of a variable, = is an operator that assigns the value to a variable, and 5 is the integer value assigned to a variable x.

Syntax
<data type> <variable name> = <value>;

The following declares and initializes a variable of an int type.

Example: C# Variable
int num = 100;

Above, int is a data type, num is a variable name (identifier). The = operator is used to assign a value to a variable. The right side of the = operator is a value that will be assigned to left side variable. Above, 100 is assigned to a variable num.

The following declares and initializes variables of different data types.

Example: C# Variables
int num = 100;
float rate = 10.2f;
decimal amount = 100.50M;
char code = 'C';
bool isValid = true;
string name = "Steve";
Try it

The followings are naming conventions for declaring variables in C#:

  • Variable names must be unique.
  • Variable names can contain letters, digits, and the underscore _ only.
  • Variable names must start with a letter.
  • Variable names are case-sensitive, num and Num are considered different names.
  • Variable names cannot contain reserved keywords. Must prefix @ before keyword if want reserve keywords as identifiers.

C# is the strongly typed language. It means you can assign a value of the specified data type. You cannot assign an integer value to string type or vice-versa.

Example: Cannot assign string to int type variable
int num = "Steve";

Variables can be declared first and initialized later.

Example: Late Initialization
int num;
num = 100;

A variable must be assigned a value before using it, otherwise, C# will give a compile-time error.

Error: Invalid Assignment
int i;
int j = i; //compile-time error: Use of unassigned local variable 'i'

The value of a variable can be changed anytime after initializing it.

Example: C# Variable
int num = 100;
num = 200;
Console.WriteLine(num); //output: 200

Multiple variables of the same data type can be declared and initialized in a single line separated by commas.

Example: Multiple Variables in a Single Line
int i, j = 10, k = 100;
Try it

Multiple variables of the same type can also be declared in multiple lines separated by a comma. The compiler will consider it to be one statement until it encounters a semicolon ;.

Example: Multi-Line Declarations
int i = 0, 
    j = 10, 
    k = 100;
Try it

The value of a variable can be assigned to another variable of the same data type. However, a value must be assigned to a variable before using it.

Example: Variable Assignment
int i = 100;

int j = i; // value of j will be 100
Try it

Variables can be used in an expression and the result of the expression can be assigned to the same or different variable.

Example: Variable & Expression
int i = 100;

int j = i + 20; // j = 120

i = 200;
j = i + 20;// j = 220

i = 300;
Console.WriteLine("j = {0}", j);// j = 220
Try it

In the above example, value of j depends on the value of i. You must re-execute expression each time you change the value of i; otherwise, value of j would not change based on the value of i.

In C#, variables are categorized based on how they store their value in memory. Variables are categorized into value type or reference type or pointer type variables.

It is not necessary to specify the specific type when declaring variables. Use the var keyword instead of a data type. Learn about it next.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.