Variable Operations

Variable Operations

In C#, you can perform various operations on variables depending on their data types. Here are some examples:

1. Arithmetic Operations

You can perform arithmetic operations on numeric variables such as int, float, and double. Some of the arithmetic operators supported in C# are:

Addition (+)

Subtraction (-)

Multiplication (*)

Division (/)

Modulus (%)

Here’s an example of using arithmetic operators on variables:

int num1 = 10;

int num2 = 5;

int sum = num1 + num2;  // addition

int difference = num1 – num2;  // subtraction

int product = num1 * num2;  // multiplication

int quotient = num1 / num2;  // division

int remainder = num1 % num2;  // modulus

2. Comparison Operators

You can compare variables using comparison operators such as:

Greater than (>)

Less than (<)

Greater than or equal to (>=)

Less than or equal to (<=)

Equal to (==)

Not equal to (!=)

Here’s an example of using comparison operators on variables:

int num1 = 10;

int num2 = 5;

bool greaterThan = num1 > num2;  // greater than

bool lessThan = num1 < num2;  // less than

bool greaterThanOrEqualTo = num1 >= num2;  // greater than or equal to

bool lessThanOrEqualTo = num1 <= num2;  // less than or equal to

bool equalTo = num1 == num2;  // equal to

bool notEqualTo = num1 != num2;  // not equal to

3. Concatenation

You can concatenate string variables using the + operator. Here’s an example:

string firstName = “John”;

string lastName = “Doe”;

string fullName = firstName + ” ” + lastName;

In this example, the variables “firstName” and “lastName” are concatenated with a space to create a “fullName” variable.

These are just a few examples of the operations you can perform on variables in C#. The language provides a rich set of operators and functions that you can use to manipulate variables and perform complex computations.

You can use all the standard types of variable operations in C#. When working with numbers, you can use various math symbols, as listed in below table. C# follows the conventional order of operations, performing exponentiation first, followed by multiplication and division and then addition and subtraction. You can also control order by grouping subexpressions with parentheses:

int number;

number = 4 + 2 * 3;

// number will be 10.

number = (4 + 2) * 3;

// number will be 18.

Arithmetic Operations

OperatorDescriptionExample
+Addition1 + 1 = 2
Subtraction5 – 2 = 3
*Multiplcation2 * 5 = 10
/Division5.0 / 2 = 2.5
%Mod200 % 4 = 8

The addition operator can also be used to join two strings. For example:

myName = firstName + ” ” + lastName;

Apply for ASP.NET Certification Now!!

https://www.vskills.in/certification/certified-aspnet-programmer

Back to Tutorial

Variables and Data Types
Conditional Logic

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?