C# Variables & Operators with Example

โšก Smart Summary

C# variables name storage locations that hold typed values, while operators perform actions such as arithmetic, comparison, and logic on those values. Together they form the foundation of every expression and calculation a C# program executes.

  • ๐Ÿ“ฆ Variables: A variable is a named storage area whose data type fixes the size, layout, and valid operations for its value.
  • ๐Ÿ”ค Declaration: Declaring a String and an Int32 shows how C# holds text and whole numbers, then prints them with Console.Write.
  • โž— Operator groups: Arithmetic, relational, and logical operators cover math, comparisons, and Boolean checks that drive program decisions.
  • ๐Ÿงฎ Assignment and bitwise: Compound operators such as plus-equals shorten updates, while bitwise operators work on the individual bits of integer values.
  • ๐Ÿ”ข Precedence: Operator precedence and associativity decide the order in which C# evaluates the parts of a complex expression.
  • ๐Ÿค– AI assistance: GitHub Copilot and ML.NET help generate variable declarations, operator logic, and map values into machine learning features.

C# Variables and Operators

C# Variables

A variable is a name given to a storage area that is used to store values of various data types. Each variable in C# needs to have a specific type, which determines the size and layout of the variableโ€™s memory.

For example, a variable can be of the type String, which means that it will be used to store a string value. Based on the data type, specific operations can be carried out on the variable.

For instance, if we had an Integer variable, then operations such as addition and subtraction can be carried out on the variable. One can declare multiple variables in a program.

Letโ€™s look at a quick example of the declaration of multiple variables of different data types.

In our example, we will define two variables, one of the type โ€˜stringโ€™ and the other of the type โ€˜Integerโ€™. We will then display the values of these variables to the console. For each example, we will modify just the main function in our Program.cs file.

C# Variables

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
 class Program 
 {
  static void Main(string[] args) 
  {
   String message="The value is ";
   Int32 val=30;
   
   Console.Write(message+val);
   Console.ReadKey();
  }
 }
}

Code Explanation:-

  1. A variable of the data type String is declared. The name of the variable is โ€˜messageโ€™. The value of the variable is โ€œThe value is โ€œ.
  2. A variable of the data type Integer (Int32) is declared. The name of the variable is โ€˜valโ€™. The value of the variable is 30.
  3. Finally the Console.write statement is used to output both the value of the String and Integer variable.

If the above code is entered properly and the program is executed successfully, the following output will be displayed.

Output:

C# Variables

From the output, you can see that the values of both the string and integer variable are displayed to the console.

Now that variables can hold values, the next step is to act on those values. Operators are used to perform operations on values of various data types. For example, to perform the addition of 2 numbers, the + operator is used.

Letโ€™s see the table of operators available for the various data types.

C# Operators

Arithmetic Operators

These are operators used for performing mathematical operations on numbers. Below is the list of operators available in C#.

Operator Description
+ Adds two operands
โ€“ Subtracts the second operand from the first
* Multiplies both operands
/ Divides the numerator by de-numerator
% Modulus Operator and a remainder of after an integer division
++ Increment operator increases integer value by one
โ€” Decrement operator decreases integer value by one

Relational Operators

These are operators used for performing Relational operations on numbers. Below is the list of relational operators available in C#.

Operator Description
== Checks if the values of two operands are equal or not, if yes then condition becomes true.
!= Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

Logical Operators

These are operators used for performing Logical operations on values. Below is the list of operators available in C#.

Operator Description
&& This is the Logical AND operator. If both the operands are true, then condition becomes true.
|| This is the Logical OR operator. If any of the operands are true, then condition becomes true.
! This is the Logical NOT operator.

Letโ€™s look at a quick example of how the operators can be used in .NET.

In our example, we will define 2 Integer variables and one Boolean variable. We will then perform arithmetic, relational, and logical operations on them.

C# Operators

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
 class Program 
 {
  static void Main(string[] args) 
  {
   Int32 val1 = 10,val2 = 20;
   bool status = true;
   
   Console.WriteLine(val1 + val2);
   Console.WriteLine(val1 < val2);
   Console.WriteLine(!(status));
   Console.ReadKey();
  }
 }
}

Code Explanation:-

  1. Two Integer variables are defined, one being val1 and the other being val2. These will be used to showcase relational and arithmetic operations. A Boolean variable is defined to showcase logical operations.
  2. An example of the arithmetic operation is shown wherein the addition operator is carried out on val1 and val2. The result is written to the console.
  3. An example of the relational operation is shown wherein the less than operator is carried out on val1 and val2. The result is written to the console.
  4. An example of the logical operation is shown, wherein the logical operator (!) is applied to the status variable. The logical NOT operator reverses the current value of any Boolean value. So if a Boolean value is โ€˜trueโ€™, the logical NOT will return the value โ€˜falseโ€™ and vice versa. In our case since the value of the status variable is โ€˜trueโ€™, the result will show โ€˜falseโ€™. The result is written to the console.

If the above code is entered properly and the program is executed successfully, the output will be displayed.

Output:

C# Operators

C# Assignment Operators

Assignment operators store the result of an expression in a variable. The basic assignment operator is the single equals sign, and C# also provides compound operators that combine assignment with an arithmetic or bitwise operation. These shorthand forms keep update statements short and easy to read.

Operator Description
= Assigns the value of the right operand to the left operand
+= Adds the right operand to the left operand and assigns the result
-= Subtracts the right operand from the left operand and assigns the result
*= Multiplies both operands and assigns the result to the left operand
/= Divides the left operand by the right operand and assigns the result
%= Takes the modulus of both operands and assigns the remainder to the left operand

For example, writing count += 5 is a shorter way to write count = count + 5. Compound assignment operators work with every arithmetic operator and with the bitwise operators as well, so they appear often inside loops and counters where a value is updated repeatedly.

C# Bitwise Operators

Bitwise operators act on the individual bits of integer values rather than on the whole number. They are useful for low-level tasks such as setting flags, masking values, and performing fast multiplication or division by powers of two.

Operator Description
& Bitwise AND sets each result bit to 1 only when both matching bits are 1
| Bitwise OR sets each result bit to 1 when either matching bit is 1
^ Bitwise XOR sets each result bit to 1 only when the two matching bits differ
~ Bitwise complement inverts every bit of its single operand
<< Left shift moves the bits to the left and fills the empty positions with zeros
>> Right shift moves the bits to the right by the given number of positions

For instance, the expression 5 & 3 compares the bits of both numbers and returns 1. Because a single left shift doubles a value, bitwise operators can make some calculations faster than their arithmetic equivalents, which matters in graphics and embedded code.

C# Operator Precedence and Associativity

When an expression contains several operators, C# does not simply evaluate them from left to right. Operator precedence sets the order in which different operators run, and associativity decides the order when two operators share the same precedence.

  • Precedence: Multiplication and division run before addition and subtraction, so 2 + 3 * 4 gives 14, not 20.
  • Left associativity: Most binary operators group from left to right, so a – b – c is evaluated as (a – b) – c.
  • Right associativity: The assignment and conditional operators group from right to left, so x = y = z assigns z to y first.
  • Parentheses: Wrapping part of an expression in parentheses overrides the default order and makes the intended calculation clear.

Relying on parentheses instead of memorizing the full precedence table keeps complex expressions readable and helps prevent subtle calculation bugs.

FAQs

A variable can change its value during execution, while a constant, declared with the const keyword, is fixed at compile time and never changes. Use variables for data that updates and constants for values such as Pi that stay the same.

The var keyword lets the compiler infer a local variableโ€™s type from its initializer, so var count = 10 creates an int. The variable is still strongly typed; var only removes the need to write the type name explicitly.

A single equals sign is the assignment operator, which stores a value in a variable. A double equals sign is the equality operator, which compares two values and returns true or false. Confusing the two is a common beginner mistake.

A unary operator works on one operand, such as the ! logical NOT or the ++ increment. A binary operator works on two operands, such as + for addition or && for logical AND. C# also has one ternary operator.

The ternary operator ?: is a shorthand for an if-else statement. It evaluates a condition, then returns the first value when the condition is true and the second when it is false, as in int max = a > b ? a : b.

The null-coalescing operator ?? returns its left operand when that value is not null, otherwise it returns the right operand. For example, name ?? โ€œGuestโ€ supplies a default. The ??= variant assigns a value only when the target is currently null.

Yes. GitHub Copilot suggests variable declarations, operator expressions, and compound assignments inside Visual Studio and VS Code, and can complete a calculation from a comment. Review each suggestion for correct data types and the intended order of precedence.

ML.NET pipelines rely on C# variables to hold features and labels, and on operators to normalize or combine them before training. Numeric and Boolean values map cleanly to model inputs, which keeps a machine learning workflow strongly typed and predictable.

Summarize this post with: