In C#, operators are special symbols or keywords that perform operations on one or more operands. C# provides a wide range of operators for performing various tasks, including mathematical calculations, logical operations, and more.
int a = 2;
int b = 3;
int sum = a + b; // returns 5
int difference = a - b; // returns -1
int product = a * b; // returns 6
int quotient = a / b; // returns 0 because quotient is an int. C# ALWAYS rounds down.
int remainder = a % b; // returns 2
For any of the arithmetic operators, if an equal sign is added on to the original sign, it will assign the result of the operation to the variable. For example..
int sum = 2;
int sum = sum + 2;
int sum += 2;
// the last two lines of code accomplish the same task.
//The latter looks cleaner which is why most people prefer to use that way
sum =+ 2; // this will NOT work.
When comparing objects(such as strings and other custom classes) you use the method .Equals(). Using == may give inaccurate results. We will talk more about this when we get into Object-Oriented Programming.
int a = 2;
int b = 2;
bool equals = a == b; // returns true
bool notequals = a != b; // returns false
// we are using == instead of .Equals() because int is primitive.
bool lessThan = a < b; // returns false
bool lessThanOrEqual = a <= b; // returns true
int a = 2;
int b = 2;
bool doubleEquals = (a == b) && (b == 2); // returns true
doubleEquals = (a == b) && (b == 3); // returns false because both
//conditions in parentheses are not true
bool oneIsEqual = (a == b) || (b == 3); // returns true because
//one of the conditions in parentheses is true
bool not = !(a == b); // returns false because the NOT operator
//takes the opposite of (a==b) --> true.
// The opposite of true is false.
With a bank account, there are two main actions that you can do. Depositing and withdrawing. Right now, I will add two methods in order to simulate depositing and withdrawing money.
static double DepositBalance(double balance, double additionalBalance)
{
return balance + additionalBalance;
}
static double WithdrawBalance(double balance, double balanceToSubtract)
{
return balance - balanceToSubtract;
}
Below the main method, I have created two new methods DepositBalance and WithdrawBalance. As you can see, their purpose is very simple; adding and subtracting balance.
All the code:
internal class Program
{
static void Main(string[] args)
{
string name = "John Doe";
int age = 13;
double balance = 500.00;
balance = DepositBalance(balance, 250);
Console.WriteLine(balance);
}
static double DepositBalance(double balance, double additionalBalance)
{
return balance + additionalBalance;
}
static double WithdrawBalance(double balance, double balanceToSubtract)
{
return balance - balanceToSubtract;
}
}