Variables, Data Types, and Operators in C#
Variables, data types, and operators form the foundation of any programming language, including C#. In this section, we'll explore these fundamental aspects of C# programming.
Variables
Variables in C# are elements in a program that can hold values. A variable has a name and a type, and it can be assigned a value. For example:
int number = 10;
In this example, int is the variable type, number is the variable name, and 10 is the value that is stored in the variable.
Data Types
C# is a statically typed language, which means that the type of every variable is known at compile time. Here are some of the most common data types in C#:
- int: The int data type is used to store integers, which are whole numbers without a fractional component. It can store values between -2,147,483,648 and 2,147,483,647.
- double: The double data type is used to store floating-point numbers, which are numbers with a decimal component.
- bool: The bool data type is used to store Boolean values, which can be either true or false.
- char: The char data type is used to store single characters.
- string: The string data type is used to store sequences of characters, or text.
int age = 30; double averageScore = 85.6; bool isMarried = true; char initial = 'A'; string name = "John Doe";
Operators
Operators in C# are special symbols that perform specific operations on one, two, or three operands, and then return a result. C# includes several types of operators:
- Arithmetic Operators: These operators perform arithmetic operations with numeric operands. For example, +, -, *, /, and %.
- Assignment Operators: These operators assign a value to a variable. The most common assignment operator is =.
- Comparison Operators: These operators compare two operands. They include == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to).
- Logical Operators: These operators perform logical operations and return a Boolean result. The logical operators in C# include && (logical and), || (logical or), and ! (logical not).
int a = 10; int b = 20; int c = a + b; // Arithmetic Operator bool isALessThanB = a < b; // Comparison Operator
Reference:
- Docs: https://www.tutorialsteacher.com/csharp/csharp-data-types
- Video: https://www.youtube.com/watch?v=gfkTfcpWqAY