Wednesday, April 03, 2024

Mastery of operators in C# 12 programming language, everything you need for efficient coding

Operators in the C# programming language are crucial elements for shaping, manipulating, and processing data. Understanding their proper usage not only facilitates software development but also enables efficient and readable code. In this lesson, we will explore several key operators in C# 12 and how to masterfully apply them to achieve optimal performance and code clarity. Mastery in using operators in C# 12 involves understanding their characteristics, execution priorities, and proper 
application in various contexts.

Efficient coding requires clear, readable, and optimized code that utilizes operators appropriately to achieve desired results. This lesson covers key aspects of operator usage in C# 12 and provides guidelines for achieving efficient and readable code, even if some examples go beyond beginner level. Rather than confusing or demoralizing, it should serve as guidance for your future endeavors. C# is a powerful programming language that provides various operators for data manipulation. In C# 12, some new features have been added to facilitate efficient coding.

A girl is learning programming

A girl is learning programming in C# 12 programming language

For example, “Primary Constructors”, introduced in C# 12 allow creating primary constructors in any class or structure. The parameters of the primary constructor are available throughout the class body. Adding a primary constructor prevents the implicit generation of a parameterless constructor. “Collection Expressions”, with the introduction of a new syntax, allow creating common collections. This includes array initialization and collection initialization. These operators and functionalities enable programmers to write efficient and readable C# code.

However, we will learn about these concepts when we cover classes, constructors, and collections. Meanwhile, we’ll primarily introduce more important operators through practical examples to ensure better understanding. In this lesson, you’ll be typing a lot and getting accustomed to writing code extensively. In C# programming language, operators have their own precedence when they are executed. For example, multiplication will always be performed before addition. Therefore, it is necessary and safer to always use parentheses before you find yourself in a situation where operator precedence leads to an incorrect result.

int number = 4 + 5 * 6; // Result is 34

 

// You might have expected the result to be 54

// Always use parentheses to clarify expressions

 

int number = (4 + 5) * 6; // Result is 54

The computer will always perform calculations according to operator precedence unless you change it with parentheses.

Mastering Arithmetic Operators in C# 12: Efficient Calculations Made Easy

Arithmetic operators are essential elements in mathematics and programming. They allow performing basic arithmetic operations on numerical values. In programming, these operators are used for value calculation, data manipulation, and problem-solving. For example, we can use arithmetic operators to calculate averages, compute taxes, or manage financial transactions. Understanding the execution priorities of these operators is crucial to obtaining accurate results.

We can always rely on these fundamental operators to build more complex expressions and functionalities in our code. Create a new folder named “lesson 3” within the “csharp_tutorial” directory, and inside it, create a new C# 12 project named “ArithmeticOperators.” In the “Program.cs” file, enter the following code:

// ARITHMETIC OPERATORS

// MANUEL RADOVANOVIC - 2024-03-22

// www.manuelradovanovic.com


using static System.Console;


WriteLine(new string('-', 100));


// Prompt the user for the first number

Write("Enter the first number: ");

double num1 = Convert.ToDouble(ReadLine());


// Prompt the user for the second number

Write("Enter the second number: ");

double num2 = Convert.ToDouble(ReadLine());


// Perform arithmetic operations

double sum = num1 + num2;

double difference = num1 - num2;

double product = num1 * num2;

double quotient = num1 / num2;

 

// Display the results

WriteLine(new string('-', 100));

WriteLine($"The sum of {num1} and {num2} is {sum}");

WriteLine($"The difference between {num1} and {num2} is {difference}");

WriteLine($"The product of {num1} and {num2} is {product}");

WriteLine($"The quotient of {num1} divided by {num2} is {quotient}");

WriteLine(new string('-', 100));


When you complete the above program, you will get the following similar result:

---------------------------------------------------------------------------

Enter the first number: 17

Enter the second number: 10

---------------------------------------------------------------------------

The sum of 17 and 10 is 27

The difference between 17 and 10 is 7

The product of 17 and 10 is 170

The quotient of 17 divided by 10 is 1.7

---------------------------------------------------------------------------

You can see how the entire program was created and coded in the following video, too.


C# 12 - 4. How to get started with Arithmetic Operators ?

Mastering Assignment Operators in C# 12: Efficient Variable Manipulation

Assignment operators are used for assigning values to variables and performing operations on existing values. Mastery in using these operators involves efficient variable management and preventing unintended coding effects. Proper use of assignment operators include utilizing shorthand assignment forms to reduce code and improve readability. The most common assignment operator is = (equal), which assigns the right value to the left variable. Create a new project named “AssignmentOperators” in the same folder “lesson3". In the “Program.cs” file, enter the following code:

// ASSIGNMENT OPERATORS

// MANUEL RADOVANOVIC - 2024-03-22

// www.manuelradovanovic.com

 

using static System.Console;

 

WriteLine(new string('-', 100));

 

// Simple assignment operator '='

int x = 123;

WriteLine("Initial value of x: " + x);

 

WriteLine(new string('-', 100));

 

/* Add and assign '+=', subtract and assign '-=', multiply and assign '*=',

and divide and assign '/=' operators */

x += 5; // Equivalent to x = x + 5

WriteLine("After x += 5: " + x);

 

x -= 3; // Equivalent to x = x - 3

WriteLine("After x -= 3: " + x);

 

x *= 2; // Equivalent to x = x * 2

WriteLine("After x *= 2: " + x);

 

x /= 4; // Equivalent to x = x / 4

WriteLine("After x /= 4: " + x);

 

// Modulus and assign '%=' operator

x %= 7; // Equivalent to x = x % 7

WriteLine("After x %= 7: " + x);

 

/* Bitwise AND and assign '&=', OR and assign '|=', XOR and assign '^=',

   left shift and assign '<<=', and right shift and assign '>>=' operators */

x &= 6; // Equivalent to x = x & 6

WriteLine("After x &= 6: " + x);

 

x |= 3; // Equivalent to x = x | 3

WriteLine("After x |= 3: " + x);

 

x ^= 2; // Equivalent to x = x ^ 2

WriteLine("After x ^= 2: " + x);

 

x <<= 1; // Equivalent to x = x << 1

WriteLine("After x <<= 1: " + x);

 

x >>= 1; // Equivalent to x = x >> 1

WriteLine("After x >>= 1: " + x);

 

WriteLine(new string('-', 100));


When you complete the above program, you will get the following result:

---------------------------------------------------------------------------

Initial value of x: 123

---------------------------------------------------------------------------

After x += 5: 128

After x -= 3: 125

After x *= 2: 250

After x /= 4: 62

After x %= 7: 6

After x &= 6: 6

After x |= 3: 7

After x ^= 2: 5

After x <<= 1: 10

After x >>= 1: 5

---------------------------------------------------------------------------

You can see how the entire program was created and coded in the following video, too.


C# 12 - 5. How to get started with Assignment Operators ?

Exploring Increment and Decrement Operators in Programming

Understanding the increment (++ operator) and decrement (-- operator) in the C# programming language is crucial for efficient variable management and flow control. These operators allow you to increase or decrease the value of a variable by one and are used in various situations, from iterating through loops to manipulating counters and indices. 

In this comprehensive program, we will explore these operators in detail, learn how to use them correctly, and understand their role in C# programming. Create a new project named “IncrementDecrementOperators” in the same folder “lesson3" In the “Program.cs” file, enter the following code: 

// INCREMENT AND DECREMENT OPERATORS

// MANUEL RADOVANOVIC - 2024-03-23

// www.manuelradovanovic.com

 

using static System.Console;

 

WriteLine(new string('-', 100));

 

// Declare an integer variable 'num' and initialize it to 500

int num = 500;

WriteLine("Initial value of num: " + num);

 

WriteLine();

 

// Post-increment: Use the value of 'num', then increment it by 1

WriteLine("Post-increment (num++): " + num++);

WriteLine("Value of num after post-increment: " + num);

 

WriteLine();

 

// Post-decrement: Use the value of 'num', then decrement it by 1

WriteLine("Post-decrement (num--): " + num--);

WriteLine("Value of num aftr post-decrement: " + num);

 

WriteLine();

 

// Pre-increment: Increment 'num' by 1, then use the new value

WriteLine("Pre-increment (++num): " + ++num);

WriteLine("Value of num after pre-increment: " + num);

 

WriteLine();

 

// Pre-decrement: Decrement 'num' by 1, then use the new value

WriteLine("Pre-decrement (--num): " + --num);

WriteLine("Value of num after pre-decrement: " + num);

 

WriteLine(new string('-', 100));

 

When you complete the above program, you will get the following result:

---------------------------------------------------------------------------

Initial value of num: 500

 

Post-increment (num++): 500

Value of num after post-increment: 501

 

Post-decrement (num--): 501

Value of num aftr post-decrement: 500

 

Pre-increment (++num): 501

Value of num after pre-increment: 501

 

Pre-decrement (--num): 500

Value of num after pre-decrement: 500

---------------------------------------------------------------------------

You can see how the entire program was created and coded in the following video, too.


C# 12 - 6. How to get started with Increment and Decrement Operators ? 

Mastering Logical Operators in Programming

Logical operators (&&, ||, !) are used for evaluating logical expressions and controlling program flow. Efficiently using these operators involves understanding short-circuit evaluations and short-circuit logical operators, which can improve program performance and avoid unnecessary execution of additional operations. For example, using the short-circuit logical AND operator (&&) allows the evaluation to terminate as soon as the first false value is encountered. This can be useful in situations where avoiding unnecessary operations is necessary. Create a new project named “LogicalOperators” in the same folder “lesson3". In the “Program.cs” file, enter the following code:

 

// LOGICAL OPERATORS

// MANUEL RADOVANOVIC - 2024-03-22

// www.manuelradovanovic.com

 

using static System.Console;

 

WriteLine(new string('-', 100));

 

// Prompt the user to enter boolean values

Write("Enter a boolean value for a (true or false): ");

bool a = Convert.ToBoolean(ReadLine());

 

Write("Enter a boolean value for b (true or false): ");

bool b = Convert.ToBoolean(ReadLine());

WriteLine(new string('-', 100));

 

// Display the entered values

WriteLine("Value of a: " + a);

WriteLine("Value of b: " + b);

 

// '&&' is the logical AND operator// It returns true if both operands are true

bool andResult = a && b;

WriteLine("Logical AND (a && b): " + andResult);

 

// '||' is the logical OR operator

// It returns true if at least one operand is true

bool orResult = a || b;

WriteLine("Logical OR (a || b): " + orResult);

 

// '!' is the logical NOT operator

// It inverts the value of a boolean, true becomes false and vice versa

bool notResult = !a;

WriteLine("Logical NOT (!a): " + notResult);

 

// Combining logical operators

bool complexResult = (a && b) || (!a && b);

WriteLine("Combining logical operators: " + complexResult);

 

// Using logical operators in conditions

if (a && !b)

{

    WriteLine("Condition is: True");

}

else

{

    WriteLine("Condition is: False");

}

 

WriteLine(new string('-', 100));


When you complete the above program, you will get the following similar result:

---------------------------------------------------------------------------

Enter a boolean value for a (true or false): True

Enter a boolean value for b (true or false): False

---------------------------------------------------------------------------

Value of a: True

Value of b: False

Logical AND (a && b): False

Logical OR (a || b): True

Logical NOT (!a): False

Combining logical operators: False

Condition is: True

---------------------------------------------------------------------------

You can see how the entire program was created and coded in the following video, too.


C# 12 - 7. How to get started with Logical Operators ?

Exploring Relational Operators in Programming

Relational operators are crucial for decision-making in programming. They allow programmers to set conditions that determine the flow of program execution based on variable values or expressions. Proper use of relational operators enables the development of software that functions correctly and reliably in various situations. Additionally, relational operators form the foundation for controlling program flow. They enable conditional execution of specific code blocks, which is essential for implementing various. Create a new project named “RelationalOperators” in the same folder “lesson3". In the “Program.cs” file, enter the following code:

 

// RELATIONAL OPERATORS

// MANUEL RADOVANOVIC - 2024-03-25

// www.manuelradovanovic.com

 

using static System.Console;

 

WriteLine(new string('-', 100));

 

// Prompt the user to enter values

WriteLine("Enter a value for a: ");

int a = Convert.ToInt32(ReadLine());

 

WriteLine("Enter a value for b: ");

int b = Convert.ToInt32(ReadLine());

 

WriteLine(new string('-', 100));

 

// '==' checks if two operands are equal

bool areEqual = a == b;

Write("Are a and b equal? " + areEqual);

 

// '!=' checks if two operands are not equal

bool areNotEqual = a != b;

Write("Are a and b not equal? " + areNotEqual);

 

// '>' checks if left operand is greater than right operand

bool isAGreater = a > b;

WriteLine("Is a greater than b? " + isAGreater);

 

// '<' checks if left operand is less than right operand

bool isALess = a < b;

WriteLine("Is a less than b? " + isALess);

 

// '>=' checks if left operand is greater than or equal to right operand

bool isAGreaterOrEqual = a >= b;

WriteLine("Is a greater than or equal to b? " + isAGreaterOrEqual);

 

// '<=' checks if left operand is less than or equal to right operand

bool isALessOrEqual = a <= b;

WriteLine("Is a less than or equal to b? " + isALessOrEqual);

 

WriteLine(new string('-', 100));


When you complete the above program, you will get the following similar result:

---------------------------------------------------------------------------

Enter a value for a: 43

Enter a value for b: 12

---------------------------------------------------------------------------Are a and b equal? False

Are a and b not equal? True

Is a greater than b? True

Is a less than b? False

Is a greater than or equal to b? True

Is a less than or equal to b? False

---------------------------------------------------------------------------

You can see how the entire program was created and coded in the following video, too.


C# 12 - 8. How to get started with Relational Operators ? 

Demystifying Bitwise Operators in Programming

Bitwise operators allow manipulation of data bits. For efficient coding, it’s important to understand how these operators apply to binary data and how they’re used for specific operations, such as bit masking or left and right bit shifting. Using bitwise operators can be beneficial in situations that require fast operations on binary data, such as hardware communication or data encryption. Create a new project named “BitwiseOperators” in the same folder “lesson3". In the “Program.cs” file, enter the following code:

 

// BITWISE OPERATORS

// MANUEL RADOVANOVIC - 2024-03-22

// www.manuelradovanovic.com

 

using static System.Console;

 

WriteLine(new string('-', 100));

 

// Define variables 'a' and 'b' with new values

int a = 78; // Binary representation: 0100 1110

int b = 23; // Binary representation: 0001 0111

 

// Display the values of 'a' and 'b'

WriteLine("Value of a: " + a);

WriteLine("Value of b: " + b);

 

WriteLine(new string('-', 100));

 

// '&' is the bitwise AND operator

int andResult = a & b; // Binary result: 0000 0110

WriteLine("Bitwise AND (a & b): " + andResult);

 

// '|' is the bitwise OR operator

int orResult = a | b; // Binary result: 0101 1111

WriteLine("Bitwise OR (a | b): " + orResult);

 

// '^' is the bitwise XOR operator

int xorResult = a ^ b; // Binary result: 0101 1001

WriteLine("Bitwise XOR (a ^ b): " + xorResult);

 

// '~' is the bitwise NOT operator

int notResult = ~a; // Binary result will vary depending on system architecture

WriteLine("Bitwise NOT (~a): " + notResult);

 

// '<<' is the left shift operator

int leftShift = a << 2; // Binary result: 1001 1100

WriteLine("Left Shift (a << 2): " + leftShift);

 

// '>>' is the right shift operator

int rightShift = a >> 2; // Binary result: 0001 0011

WriteLine("Right Shift (a >> 2): " + rightShift);

 

WriteLine(new string('-', 100));


When you complete the above program, you will get the similar following result:

---------------------------------------------------------------------------

Value of a: 78

Value of b: 23

---------------------------------------------------------------------------

Bitwise AND (a & b): 6

Bitwise OR (a | b): 95

Bitwise XOR (a ^ b): 89

Bitwise NOT (~a): -79

Left Shift (a << 2): 312

Right Shift (a >> 2): 19

---------------------------------------------------------------------------

You can see how the entire program was created and coded in the following video, too.


C# 12 - 9. How to get started with Bitwise Operators ?

Understanding the Ternary Operator in Programming

The ternary operator, often referred to as the conditional operator, is a unique construct in the C# programming language that allows decision-making based on a single condition. This operator provides an elegant way to execute conditional expressions with just one line of code. It is particularly useful when making simple decisions based on a single condition, reducing complexity and enhancing code readability.

Additionally, the ternary operator is frequently used in combination with other language constructs, such as lambda expressions, LINQ queries, or delegates, enabling elegant expression of logic in various parts of C# applications. Create a new project named “TernaryOperator” in the same folder “lesson3". In the “Program.cs” file, enter the following code:

// TERNARY OPERATOR

// MANUEL RADOVANOVIC - 2024-03-23

// www.manuelradovanovic.com

 

using static System.Console;

 

WriteLine(new string('-', 100));

 

// Prompt the user to enter the temperature in Celsius

Write("Please enter the temperature in Celsius: ");

int temperature = Convert.ToInt32(Console.ReadLine());

 

// Use the ternary operator to determine the weather description

string weatherDescription = temperature > 30 ? "hot" : "pleasant";

 

// Output the result

WriteLine($"The weather is {weatherDescription}.");

 

WriteLine(new string('-', 100));


When you complete the above program, you will get the similar following result:

---------------------------------------------------------------------------

Please enter the temperature in Celsius: 27

The weather is pleasant.

---------------------------------------------------------------------------

You can see how the entire program was created and coded in the following video, too.


C# 12 - 10. How to get started with Ternary Operator ?

Exploring the Elvis Operator in Programming

The Elvis operator, also known as the null-conditional operator, is a useful tool in the C# programming language that allows safe navigation through objects that can be null without triggering null reference exceptions. This operator enables programmers to make chained property or method calls on potentially null objects, reducing the need for manual null value checks and enhancing code readability.

The Elvis operator is often used in combination with LINQ queries, lambda expressions, or in situations where safe access to properties or method invocations of potentially null objects is required. It can be particularly helpful when dealing with complex object hierarchies. Create a new project named “ElvisNullConditionalOperator” in the same folder “lesson3". In the “Program.cs” file, enter the following code:

 

// ELVIS OR NULL-CONDITIONALS OPERATOR

// MANUEL RADOVANOVIC - 2024-03-23

// www.manuelradovanovic.com

 

using static System.Console;

 

WriteLine(new string('-', 100));

 

// Create a new Person instance

var person = new Person();

 

// Prompt the user for their first name, last name, and country

Write("Please enter your first name: ");

person.FirstName = Console.ReadLine();

 

Write("Please enter your last name: ");

person.LastName = Console.ReadLine();

 

Write("Please enter your country: ");

person.Country = Console.ReadLine();

 

// Use the Elvis operator to safely access the properties and provide default values

string displayName = $"{person.FirstName?.Trim() ?? "No first name provided"} {person.LastName?.Trim() ?? "No last name provided"}";

string displayCountry = person.Country?.Trim() ?? "No country provided";

 

WriteLine();

 

// Output the result

WriteLine($"Name: {displayName}");

WriteLine($"Country: {displayCountry}");

 

WriteLine(new string('-', 100));

 

// Define the Person class with nullable properties

public class Person

{

    public string? FirstName { get; set; }

    public string? LastName { get; set; }

    public string? Country { get; set; }

}


When you complete the above program, you will get the similar following result:

---------------------------------------------------------------------------

Please enter your first name: Manuel

Please enter your last name:

Please enter your country: Serbia

 

Name: Manuel

Country: Serbia

---------------------------------------------------------------------------

You can see how the entire program was created and coded in the following video, too.


C# 12 - 11. How to get started with Elvis Null-Conditional Operator

Demystifying Lambda Operator in Expressions

Lambda expressions are often used in situations where defining short and simple functions on the spot is necessary. Lambda expressions are a powerful concept in C# that allows defining anonymous functions inline. Using lambda expressions can significantly improve readability, reduce code volume, and enhance flexibility in software development. These expressions are particularly useful in scenarios such as LINQ queries, delegates, and events, where functions are frequently used as arguments to other functions or delegates. Create a new project named “LambdaOperatorInExpressions” in the same folder “lesson3". In the “Program.cs” file, enter the following code:

 

// LAMBDA OPERATOR IN EXPRESSIONS

// MANUEL RADOVANOVIC, 2024-03-23

// www.manuelradovanovic.com

 

using static System.Console;

 

WriteLine(new string('-', 100));

 

// Lambda expression to calculate the square of a number

Func<int, int> square = num => num * num;

WriteLine("Square of 5: " + square(5)); // Output: Square of 5: 25

 

// Lambda expression to check if a number is even

Func<int, bool> isEven = num => num % 2 == 0;

WriteLine("Is 4 even? " + isEven(4)); // Output: Is 4 even? True

 

// Lambda expression with no input parameters

Action greet = () => WriteLine("C# 12 Programming Language");

greet(); // Output: C# 12 Programming Language

 

// Lambda expression to concatenate two strings

Func<string, string, string> concat = (str1, str2) => str1 + str2;

 

// Output: Concatenation result: Lambda Expressions

WriteLine("Concatenation result: " + concat("Lambda ", "Expressions"));

 

// Using lambda expression with LINQ

int[] numbers = { 2, 3, 4, 5 };

var squaredNumbers = numbers.Select(num => num * num);

 

// Output: Squared numbers: 4, 9, 16, 25

WriteLine("Squared numbers: " + string.Join(", ", squaredNumbers));

 

WriteLine(new string('-', 100));


When you complete the above program, you will get the following result:

---------------------------------------------------------------------------

Square of 5: 25

Is 4 even? True

C# 12 Programming Language

Concatenation result: Lambda Expressions

Squared numbers: 4, 9, 16, 25

--------------------------------------------------------------------------- 

You can see how the entire program was created and coded in the following video, too.


C# 12 - 12. How to get started with Lambda Operator in Expressions ?

Navigating Type Conversions in Programming

Understanding type conversions in the C# programming language is an important topic related to the process of converting values from one type to another. In C#, data types are fundamental concepts that define the kind of data we can use and how we can manipulate that data. During software development, it is often necessary to convert values between different types for compatibility, validation, or calculations.

In this comprehensive program, we will explore the process of navigating type conversions in C#, different conversion methods, and how to properly manage data types. Create a new project named “LambdaOperatorInExpressions” in the same folder “lesson3". In the “Program.cs” file, enter the following code:

 

// TYPES CONVERSION OPERATORS

// MANUEL RADOVANOVIC, 2024-03-23

// www.manuelradovanovic.com

 

using static System.Console;

 

WriteLine(new string('-', 100));

 

// Implicit Conversion Example

int numInt = 123; // Integer value

double numDouble = numInt; // Implicitly converted to double

WriteLine($"Implicit Conversion: {numInt} to {numDouble}");

 

// Explicit Conversion (Casting) Example

double numDouble2 = 123.45; // Double value

int numInt2 = (int)numDouble2; // Explicitly cast to integer

WriteLine($"Explicit Conversion: {numDouble2} to {numInt2}");

 

// Using the user-defined conversionsclear

var digit = new Digit(7); // Create a Digit instance

byte number = digit; // Implicitly convert Digit to byte

WriteLine($"User-Defined Implicit Conversion: Digit to byte: {number}");

Digit digit2 = (Digit)number; // Explicitly convert byte to Digit

WriteLine($"User-Defined Explicit Conversion: byte to Digit: {digit2.Value}");

 

WriteLine(new string('-', 100));

 

// User-Defined Conversion (Custom Casting) Example

public readonly struct Digit

{

    private readonly byte digit;

    public Digit(byte digit)

    {

        if (digit > 9)

        {

            throw new ArgumentOutOfRangeException(nameof(digit), "Digit cannot be greater than nine.");

        }

        this.digit = digit;

    }

 

    // Implicit conversion from Digit to byte

    public static implicit operator byte(Digit d) => d.digit;

 

    // Explicit conversion from byte to Digit

    public static explicit operator Digit(byte b) => new Digit(b);

 

    // Property to access the digit value

    public byte Value => digit;

   

}


When you complete the above program, you will get the following result:

---------------------------------------------------------------------------

Implicit Conversion: 123 to 123

Explicit Conversion: 123.45 to 123

User-Defined Implicit Conversion: Digit to byte: 7

User-Defined Explicit Conversion: byte to Digit: 7

---------------------------------------------------------------------------

You can see how the entire program was created and coded in the following video, too.


C# 12 - 13. How to get started with Types Conversion Operators


 

 

 


 

No comments:

Post a Comment