How to use for Loop in C#
Hello friends, I hope you all are doing great. In today's tutorial, we are gonna have a look at How to use For Loop in C#. It's our 11th tutorial in C# series. Till now, we have seen two loops in C# which are IF Loop and while Loop and today we are gonna have a look at for Loop.
For Loop is most commonly used loop in any programming language and if you have worked on any other language then you must be aware of its syntax. It is used to create repeated loop with specified number. Let's have a look at it in detail:
How to use for Loop in C#
- For loop in C# takes an integer variable as a Controlling agent, initialized at value V1 and ends at value V2, and the travel from value V1 to V2 depends on the Condition specified in () brackets.
- In both IF loop & while loop, the small brackets just have single argument, but in for loop, the small brackets have 3 arguments, separated by semicolon ; , which are:
- First argument is initial value of variable V1.
- Second argument is final value of variable V2.
- Third argument is the condition applies on this variable i.e. increment, decrement etc.
- The loop will keep on repeating itself and we will also have the value of iteration in the form of variable value.
- Let's have a look at its syntax:
for (Initial Value V1; Final Value V2; Condition)
{
// body of for loop
}
- Now let's have a look at a simple for loop in action
- Now you can see in above figure that I have initialized an integer variable x and in for loop, I have first assigned the initial value x=0 in first argument.
- In second argument, separated by ; , I have specified the final value x<10.
- Finally in third argument, I have incremented the variable x++.
- So, now when the compiler will first reach for loop, it will get x=0 and will run the code inside { } brackets that's why when I printed the value of x, it was 0 at first.
- After running all the lines in { } brackets, compiler will run the condition, which is to increment the variable, so in second iteration, the value of x=1, that's why in second line we have 1 on console.
- So, this loop will keep on running and the variable will keep on incrementing and when it will reach x=9, it will run the code lines in { } brackets and at the end it will increment the variable and will make it x = 10.
- So, now at x=10, the compiler knows in second argument of For loop, the variable's last value is 9 i.e. x <10. So when the value is not x<10, the compiler will leave for loop and go to next line below for loop.
- So, that's how For loop works, we can use it for running some lines of code repeatedly and the use of this variable inside for loop is quite helpful.
- Here's an example, where I have decremented the variable in third argument:
- From the console, its quite evident that now the variable's value is decreasing from 10 to 1, I have used x - - in condition part of For Loop.
- Now let's create an array of students' names and display all elements of that array using for Loop, we have discussed How to use Arrays in C# in our 6th lecture, you should recall that as well.
- Here's the code and it's output on console:
- As you can see in above figure that first I have initialized a new String Array of size 5.
- After that added some data i.e. students names, in each element of C# array.
- Next, I have used for Loop and initialized the variable and also assigned the first value 0 in first argument.
- In the second argument, I have used a Length property of array and our array's length is 5.
- So, this for loop will run from 0 to 4 and we can see at the console output that it has printed all the elements of array i.e. students names.
- That's how, we can use for Loop in C#, now let's have a look at how to use foreach loop in C#, which is kind of an extension of for loop.
How to use Foreach Loop in C#
- We have discussed Foreach Loop in our 6th tutorial on arrays and I have told you that we will discuss it in detail later, so now is the time to discuss it out.
- Foreach loop in C# is used to iterate through a collection or arrays from start till end. Collections could be ArrayList, HashTable etc. we will discuss them later.
- Let's first have a look at its syntax:
foreach (item in collections/arrays)
{
// body of foreach loop
}
- This item variable will go through the whole array and will repeat the lines of code inside { } brackets.
- So, let's rewrite our previous example with foreach loop along with for loop and look at both results:
- Now you can see in above figure that we got similar results for both loops although foreach loop is quite simple and easy to look at thus reduces your code.
- In foreach loop, we are directly accessing the elements of array, while in for loop, we are getting elements using index of array.
So, that was all about for Loop in C# and we have also had a look at foreach loop. I'm just using simple examples rite now so that you got the clear idea of these loops. We have covered all the loops now so in next tutorial, we will have a look at Methods in C#. Till then take care !!! :)
How to use while Loop in C#
Hello friends, I hope you all are great. Today, I am posting 10th tutorial in C# series and its about How to use while Loop in C#. It's gonna be a quick tutorial, as there's not much to discuss.
In our 8th tutorial in C# series, we have had a look at
How to use IF Loop in C# and we have seen that IF loop takes a Boolean expression and if it's TRUE then it allows the compiler to enter in it just once. While loop is quite similar to IF loop as it takes a Boolean expression as well but it will keep on executing again & again, so let's have a look at it in detail:
How to use while Loop in C#
- While Loop in C# takes a Boolean expression as a condition and it will keep on executing as long as the conditional expression returns true, we can say Execute while condition is TRUE.
- Here's the syntax of while loop:
while (Boolean Expression)
{
// Code will execute, while Boolean Expression is TRUE
}
- So, let's design a simple example to understand How while Loop works:
- In schools, you must have studied math tables, so I have created a simple code using while loop which asks from the user to enter table of.
- When user enters the number, the program will print out its table till 10.
- If you look at the code, I have used while loop and this while loop will execute 10 times as the condition in while loop is TotalLength <= 10.
- I have incremented this TotalLength variable in while Loop so when it will become 10, the while loop will stop.
- So, instead of writing 10 lines to display table, we are just using while loop, we can also increase the lines to 20 or 30 quite easily, that's the benefit of while loop.
- Let's play with the code a little and print values till 20 and also use IF Loop in this while loop, which we have studied in 8th lecture.
- You can see in above code that I have increased the length to 20 and then in while Loop, I have used IF Loop.
- IF the length is 10 then I am just adding blank lines to separate first 10 from last 10.
- I hope you got the idea of How to use While Loop and what's its difference from IF Loop, the IF Loop executed just once when condition comes true.
- Here's the complete code used in today's lecture:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Table of : ");
int TableOf = int.Parse(Console.ReadLine());
int TotalLength = 1;
while (TotalLength <= 20)
{
int TableValue = TotalLength * TableOf;
Console.WriteLine("{0} x {1} = {2}", TableOf, TotalLength, TableValue);
if(TotalLength==10)
{
Console.WriteLine("\n");
}
TotalLength++;
}
Console.WriteLine("\n\n");
}
}
}
So, that was all about How to use while Loop in C#. In our coming tutorial, we will have a loop at How to use do While Loop in C#. Till then take care !!! :)
How to use switch Statement in C#
Hello friends, I hope you all are doing great. In today's tutorial, we are gonna have a look at How to use switch Statement in C# and its our 9th tutorial in C# series. In our previous tutorial, we have seen
IF Loop in C# and this switch statement is also a loop but works slightly different than IF loop and it totally depends on your application, which one you want to use.
First we will have a look at How to use switch statement in C# and after that we will also study goto statement, because switch and goto statements are normally used together. So, let's get started with it:
How to use switch Statement in C#
- Switch Statement is a loop in C# which takes a variable as a condition, and then creates its different cases and we can deal each case separately.
- We need to use break Statement after every case Statement to get out of the switch Statement.
- We can also use default Statement at the end of switch Statement, which will execute if none of the cases are true.
- So let's have a look at the syntax of switch statement in C#:
switch (variable) {
case value1:
// This case will execute, if variable = value1
break;
case value2:
// This case will execute, if variable = value2
break;
.
.
.
case valueN:
// This case will execute, if variable = valueN
break;
default:
// default will execute, if all the above cases are false.
break;
}
- As you can see in above syntax, we have first used switch keyword and then took a variable, this variable can have any datatype.
- Then we have created different cases, we can create as many cases as we want and each case has a value so if the variable is equal to that value then respective case will execute.
- Let's understand it with an example: Let's design a project where we display information of class students using their roll number, so we will take their roll numbers as an input and will display the respective student's data using switch case statement:
- As you can see in the above figure that I have first asked for the student's Roll Number and then placed a switch statement and provided RollNo as a conditional variable.
- After that in each case I have placed the roll no value and for each roll number I have added the name and age of the user.
- In execution, I have entered 1 and the code has provided me data placed in case 1 and have ignored all the other cases as well as the default case.
- But if you run this code then you will realize that it asks for the Roll number only once but what if we want it to run again & again.
- We can use goto Statement for that purpose, although it's not the best way to create loop but one of the ways and you should know about it.
- In above code, I have just added two lines of code, first I have placed a tag Start: at the top of the code and then at the end I have used goTo Start;
- So, at the goto Statement, the compiler will find the tag mentioned and will move on to that position and will start executing the code, so it's kind of an infinite loop which is never gonna stop.
- Here's the final code, which you can test in visual studio:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
Start:
Console.Write("Please enter student's roll number: ");
int RollNo = int.Parse(Console.ReadLine());
switch(RollNo)
{
case 1:
Console.WriteLine("Name: StudentA");
Console.WriteLine("Age: 18");
break;
case 2:
Console.WriteLine("Name: StudentB");
Console.WriteLine("Age: 17");
break;
case 3:
Console.WriteLine("Name: StudentC");
Console.WriteLine("Age: 16");
break;
case 4:
Console.WriteLine("Name: StudentD");
Console.WriteLine("Age: 20");
break;
case 5:
Console.WriteLine("Name: StudentE");
Console.WriteLine("Age: 21");
break;
default:
Console.WriteLine("No student found.");
break;
}
Console.WriteLine("\n\n");
goto Start;
}
}
}
So, that was all about How to use switch Statement in C#. If you need any help then ask in comments. Will meet you in next tutorial. Till then take care !!! :)
How to use IF Loop in C#
Hello everyone, I hope you all are doing great. Today, we are gonna have a look at IF Loops in C# and it's 8th tutorial in C# series. So far, we have discussed some basic concepts in C# and now we are ready to get our hands on Loops in C#.
C#, as any other programming language, supports a lot of loop structures, we will discuss each one of them separately in our coming tutorials. Today, we will discuss the simplest of them all, which is IF loop, so let's get started with How to use IF Loop in C#:
How to use IF Loop in C#
- IF Loop in C# takes a Boolean expression as a condition and if this condition is TRUE, the compiler executes the code inside IF loop { } and if the condition is wrong, the compiler simply ignores the code.
- Here's the syntax of IF Loop in C#:
if (boolean-expression)
{
// Code will come here, execute if the Condition is TRUE.
}
- Let's create a simple program, where we ask the user to enter his Physics marks and the program will tell the user whether he is passed or failed.
- I have used If loop and the condition I have used is, if the marks are less than 50 then student has failed & if its equal or greater than 50 then the user has passed.
- Here's the code for IF loop in C#, shown in below figure:
- You can see in above figure that I have entered 25, now when the compiler will come to first IF loop, it will check the condition (Marks >= 50), which is not true as the number we entered is less than 50, so the compiler will simply ignore this IF loop and will move on to second IF Loop.
- The condition in second IF Loop is (Marks < 50), and clearly this condition is TRUE, so our compiler will enter in this IF Loop, enclosed by curly brackets { }, and will print out "You failed the exam.".
- So, in simple words:
- IF condition is TRUE => Execute.
- IF condition is FALSE => Ignore.
- Few commonly used conditional operators of IF Loops are:
- Equal to ( == )
- Not Equal to ( != )
- Greater than ( > )
- Less than ( < )
- Greater than or Equal to ( >= )
- Less than or Equal to ( <= )
- We could also use multiple conditions in single IF Loop using these two operators:
- && ( AND ) => it returns TRUE, if both conditions are TRUE.
- || ( OR ) => it returns TRUE, if either of two conditions is TRUE.
- Let's edit out code a little and add a 3rd condition, as shown in below figure:
- Here, I have used three IF Loops in above code and have used && operator in second IF Loop.
- So, if the number is in between 50 & 90, then second loop will execute, both conditions have to be TRUE.
- I hope you have understood How to use IF Loop in C#, now let's move a little forward and have a look at IF Else Loop in C#, which is kind of an extension of IF Loop.
IF-Else Loop in C#
- Instead of using separate IF Loops for different conditions, we can use single IF-Else Loop.
- In our first code, we have used two IF Loops to check whether student has passed or failed.
- Let's rewrite that code using IF-Else Loop, as shown in below figure:
- As you can see in above figure, first I have used IF Loop and placed a condition that if (Marks >= 50) then print "you passed the exam" otherwise simply print "you failed the exam".
- Else condition is like the default option, if "IF" Loop failed to execute then "ELSE" will be executed and if "IF" loop is successful, then "ELSE" will be ignored.
- That was the case for two IF Loops, but what if we have more than two IF Loops, as in our second code, we have 3 IF Loops, let's rewrite that code using IF-Else Loop:
- The above code is working exactly the same as our code with 3 IF Loops but here we are using IF-Else Loop.
- In IF-Else Loop, the first loop will be "if" loop and the last one will be "else" loop while all the intermediary loops will be "else if" loops.
- Here's the final code for today's lecture:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your Physics marks: ");
int Marks = int.Parse(Console.ReadLine());
if (Marks >= 90)
{
Console.WriteLine("You got A+ grade. \n\n");
}
else if (Marks >= 50 && Marks < 90)
{
Console.WriteLine("You passed the exam. \n\n");
}
else
{
Console.WriteLine("You failed the exam. \n\n");
}
}
}
}
So, that was all for today. I hope now you can easily use IF-Else Loop in C#, if you have any problems, ask in comments. In our next tutorial, we will have a look at How to use Switch statement in C#. Till then take care & have fun !!! :)
How to use Arrays in C# ???
Hello friends, I hope you all are having fun. In today's tutorial, we are going to discuss
How to use Arrays in C#. It's our 6th tutorial in C# series and currently we are focusing on basic concepts in C#.
Without understanding these simple concepts, we can't move forward. So, let's get started with Arrays in C#:
How to use Arrays in C# ???
- An array (base type System.Array) is a collection of similar (like-typed) data types, called by a common name. Each data item is referred as an element of array and is assigned an index starting from 0.
- As C# array is an object so we can find its length using member length, which is actually a count of total number of data items in that array.
- Arrays are reference types and implement IEnumerable that's why, we have to use new keyword for new instance of array.
- Here's an example of an array in action:
- You can see in above code that I have first initialized an array named TEPArray and I have fixed its size to 3.
- After that, I have added values in the array at each index 0, 1 and 2. If we count we have 3 positions which is the size of our array.
- After that, I am simply printing those values in the console.
Why we need to use Arrays ???
- Let's say you are working on some project where you need to show marks of some students, let's say 50 students.
- In such cases, it would be too difficult to create separate variable for each student. Instead, you can simply create an array of each subject and save all students' marks in single variable.
- In simple words, we use arrays to handle big data of similar data types.
- Arrays are strongly typed i.e. they take data of single data type, we can't add multiple data types in single array.
- We can't increase Array size after initialization, as in above code I have initialized the array with fixed size of 3 so now if I add a 4th element, then compiler will generate an error. Although, we can use foreach iteration on all arrays in C#, we will discuss that later.
Different ways to initialize Arrays in C#
- There are three different ways to initialize arrays in C#, although they are all same at the end but slightly different in syntax.
- I have shown all these three ways in below figure:
- As you can see in above code, the first way is the same one, we first initialized the array and then added values in it.
- In the second way, we have initialized the array and added values in it, in a single line.
- In the third way, I have just declared the arrays and haven't added the size or the data in it.
- After that I have initialized them and then added values, arrays don't occupy any memory unless initialized.
- Here's the complete code, which we have designed so far:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
// First Way: Initialization first & then added values
int[] TEPArray = new int[3];
TEPArray[0] = 1;
TEPArray[1] = 2;
TEPArray[2] = 3;
// Second Way: Initialization & values added in a single line
int[] TEPArray2 = new int[5] { 1, 2, 3, 4, 5 };
Console.WriteLine("Code Designed by www.TheEngineeringProjects.com \n");
Console.WriteLine("Value at Index 0 is : {0} \n", TEPArray[0]);
Console.WriteLine("Value at index 2 is : {0} \n", TEPArray[2]);
Console.WriteLine("Length of Second Array : {0} \n", TEPArray2.Length);
Console.WriteLine("First element of Second Array : {0} \n", TEPArray2[0]);
// Third Way: Declared First & then initialized & values added
string[] TEPArray3, TEPArray4;
TEPArray3 = new string[5] {"Hello","welcome","to","C#","Tutorial"};
TEPArray4 = new string[] { "Designed", "by", "The", "Engineering", "Projects" };
Console.WriteLine("\n\n");
Console.Write("For loop : ");
for (int i = 0; i < TEPArray3.Length; i++)
Console.Write(TEPArray3[i] + " ");
Console.WriteLine("\n\n");
Console.Write("For-each loop : ");
// using for-each loop
foreach (string i in TEPArray4)
Console.Write(" " + i);
Console.WriteLine("\n\n");
}
}
}
- Till now, we have discussed only One Dimensional Arrays, now let's have a look at Multi-Dimensional Arrays:
Multi-Dimensional Arrays in C#
- We have seen single row of data in arrays so far, but we can also add multiple rows in arrays and such arrays are called Multi-Dimensional Arrays or Rectangular Arrays.
- They are called rectangular because length of each row has to be same in a single array.
- Let's have a look at Multi-Dimensional Array in below figure:
- In the above code, you can see i have created two arrays, the first one TEPArray1 is a 2-Dimensional Array, while TEPArray2 is a 3-Dimensional Array.
- I have also used nested for loop to display data of 2D array, if you can't understand it yet, don't worry we will discuss it in detail in coming lectures.
- But make sure you understand, how I am accessing elements of multi-dimensional arrays.
- Here's the complete code for Multi-Dimensional Arrays in C#:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
string[,] TEPArray1 = new string[4, 2] {
{ "one", "two" },
{ "three", "four" },
{ "five", "six" },
{ "seven", "eight" }
};
int[,,] TEPArray2 = new int[2, 2, 3] {
{
{ 1, 2, 3 },
{ 4, 5, 6 }
},
{
{ 7, 8, 9 },
{ 0, 1, 2 }
}
};
// Accessing array elements.
Console.WriteLine("Code Designed by www.TheEngineeringProjects.com \n");
Console.WriteLine("2DArray[0][0] : " + TEPArray1[0, 0]);
Console.WriteLine("2DArray[0][1] : " + TEPArray1[0, 1]);
Console.WriteLine("2DArray[1][1] : " + TEPArray1[1, 1]);
Console.WriteLine("2DArray[2][0] " + TEPArray1[2, 0]);
Console.WriteLine("\n\n");
Console.WriteLine("3DArray[1][0][1] : " + TEPArray2[1, 0, 1]);
Console.WriteLine("3DArray[1][1][2] : " + TEPArray2[1, 1, 2]);
Console.WriteLine("3DArray[0][1][1] : " + TEPArray2[0, 1, 1]);
Console.WriteLine("3DArray[1][0][2] : " + TEPArray2[1, 0, 2]);
Console.WriteLine("\n\n");
Console.WriteLine("For Loop:");
for (int i = 0; i < 4; i++)
for (int j = 0; j < 2; j++)
Console.Write(TEPArray1[i, j] + " ");
Console.WriteLine("\n\n");
}
}
}
So, that was all about Arrays in C#. If you got into any errors, then ask in comments. In next lecture, we will have a look at How to use Comments in C#. Till then take care & have fun !!! :)
Datatype Conversions in C#
Hello friends, I hope you all are doing great. In today's tutorial, we are gonna have a look at Datatype Conversions in C#. We have discussed
C# Data Types in our 3rd tutorial and today we will discuss How to convert one datatype into another.
If you are working on some complex project, then you have to convert one form of data into another i.e. let's say you are getting bill value from barcode reader, this value must be a string and if you want to apply any arithmetic operation on it then you need to convert that string into integer or float. So, let's get started with Datatype Conversions in C#:
Datatype Conversions in C#
- If you are working on some data driven application, then there's always a need to convert one form of data into another and that's where Datatype Conversions are required.
- Few conversions doesn't require any method or class i.e. if we want to convert an integer into float then that can easily be done by the compiler, as there's no chance of data loss.
- Such conversions are called Implicit Conversions, here's an example:
- You can see in above figure that compiler has automatically converted integer into float.
- But if we want to convert a float (let's say 313.56) into integer then we can't do that as integer doesn't have the decimal part.
- So, if we want to convert a float into integer, we will get a compiler error i.e. overflow exception.
- In order to perform such conversions we have to use Explicit Conversions method, pre-defined in C#.
- There are two options for Explicit Conversions:
- Use Cast Operator.
- Use Convert class of C#.
- Both of these methods are shown in below figure:
- Now you can see in above figure that the Cast Operator (int) has just taken the main value and simply ignored the decimal/fractional part.
- While the Convert Class (Convert.ToInt32) has rounded off the number and didn't ignore the decimal part.
String Conversion in C#
- Normally the data received from external/hardware devices, is in the form of strings and we need to convert it into integer or float etc. to perform arithmetic operations.
- There are two options available for String Conversions in c#, which are:
- Here's the implementation of Parse Method for String to integer conversion, in below figure:
- But there's a drawback in Parse that if the string contains alphabetical / special characters then it will create an error and couldn't convert the string into integer.
- So, in order to avoid error, we should use TryParse method, as shown in below figure:
- As you can see in above figure, TryParse takes two parameters:
- First one must be a string, which you want to convert.
- Second one must be an integer, in which the value will be saved.
- Moreover, TryParse method also returns a Boolean type, which will be:
- True, if the conversion is successful.
- False, if the conversion is unsuccessful.
- I have provided a string "323ABC" whcih contains alphabetical characters, that's why ConversionCheck is false and we are not getting any value in our integer.
- Here's a screenshot of one successful conversion of TryParse method:
- Now TryParse is returning True as the conversion is successful and our output integer variable got updated.
- Here's the code used in today's tutorial:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
Console.Write("\n\nwww.TheEngineeringProjects.com\n");
string Num1 = "323";
bool ConversionCheck = int.TryParse(Num1, out int Num2);
Console.WriteLine("\nValue of Num2 : {0}", Num2);
Console.WriteLine("\nValue of ConversionCheck : {0}", ConversionCheck);
if(!ConversionCheck)
{
Console.WriteLine("\nString contains non-numeric Values.");
}
else
{
Console.WriteLine("\nOur Converted int : {0}", Num2);
}
}
}
}
So, that was all about the Datatype Conversions in C#. I hope you have enjoyed today's tutorial. In the next tutorial, we will have a look at
How to use Arrays in C#. Till then take care & have fun !!! :)
Common Operators in C#
Hello friends, I hope you all are doing great. In today's tutorial, we are going to have a look at few Common Operators in C#. It's 4th tutorial in C# series and before going forward, we have to first understand the working operation of these C# operators.
We have a lot of operators in C# but I have discussed few of them, which are most commonly used. If you got into any trouble then ask in comments. So, let's get started with Common Operators in C#:
Common Operators in C#
- Operators are used to create a link, relation or operation between two entities/variables. Few of these C# operators are as follows:
- Assignment Operator ( = )
- Arithmetic Operators ( + , - , * , / , % )
- Comparison Operators ( == , != , > , < , >= , <= )
- Conditional Operators ( && , | | )
- Ternary Operator ( ? : )
- Null Coalescing Operator ( ?? )
- Escape Sequence ( / )
- Verbatim Literal ( @ )
- Let's discuss them one by one in detail:
1. Assignment Operator ( = )
- Assignment Operator is used to assign a value from one entity to another.
- Let's say we initialize an integer with value 5, so what we need to write is int i = 5; so this assignment operator has assigned a value of 5 to integer i.
2. Arithmetic Operators ( + , - , * , / , % )
- Arithmetic Operators ( + , - , * , / , % ) are used for performing different mathematical operations between two entities/variables.
- Each arithmetic operator has its own mathematical operation associated with it. For example:
- ( + ) is used to add two numbers i.e. int a = 5 + 10; so compiler will first apply the arithmetic operator (+) and will add 5 & 10 and after that will use assignment operator to assign the value 15 to variable a.
- ( - ) is used to subtract two numbers i.e. int b = 10 - 5; result will be 5.
- ( * ) is use to multiply two numbers i.e. int c = 10 * 5; result will be 50.
- ( / ) is used to divide two numbers i.e. int d = 10 / 2; result will be 5.
- ( % ) is used to get the remainder of two numbers i.e. int e = 22 % 4; result will be 2.
3. Comparison Operators ( == , != , > , < , >= , <= )
- Comparison Operators ( == , != , > , < , >= , <= ) are used to compare two entities with one another.
- We will discuss them in detail in Loops section while discussing if loop.
- a == b, it will check whether a is equal to b.
- a != b, a is not equal to b.
- a > b, a is greater than b.
- a < b, a is less than b.
- a >= b, a is greater than or equal to b.
- a <= b, a is less than or equal to b.
- I am using few Comparison operators in this right figure.
4. Conditional Operators ( && , | | )
- Conditional Operators ( && , | | ) are used to create a relation between two conditions.
- This one will also be discussed in more detail in IF Loops section.
- && , It is pronounced as AND, this operator makes sure that both conditions must be true.
- | | , It is pronounced as OR, this operator returns TRUE if either of the two conditions is true.
- I have placed a conditional operator in right figure, I have placed a check that value must be greater than 10 and less than 20.
5. Ternary Operator ( ? : )
- Ternary operator is one of the coolest feature of C# and comes quite handy at times.
- It's a simple form of if loop, which reduces the IF Else Loop code in single line. We will discuss it in C# IF Loop lecture.
6. Null Coalescing Operator ( ?? )
- Null Coalescing Operator ( ?? ) is used to convert nullable value into non-nullable value.
- Let's say we have two integers a and b defined as:
int? a = 15; (nullable variable)
int b = 0; (non-nullable variable)
- Now we want to save value of a into b so if you write a = b; compiler will generate an error.
- So, in order to do that you need to use Null Coalescing Operator ( ?? ) as follow:
int b = a ?? 0;
- if the value of a is null, then b will become 0. It's called the default value, you can set it to anything, I've made it 0.
Complete Code
- Here's the complete code used in this tutorial:
using System;
namespace TEPProject
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Numer 1: ");
int Num1 = int.Parse(Console.ReadLine());
Console.Write("Enter Numer 2: ");
int Num2 = int.Parse(Console.ReadLine());
int Total = Num1 + Num2;
if (Total > 10 && Total < 25)
{
Console.WriteLine("Total count is {0}", Total);
}
else
{
Console.WriteLine("Total count is less than 10 or greater than 25");
}
}
}
}
I hope you have learnt something from today's tutorial. Let me know if you have any questions in comments. Take care & have fun !!! :)
C# MonthCalendar Control
Hello Everyone! I'm back to give you daily dose of information that resonates with your needs and requirements. Today, I'm going to uncover the details on the introduction to
C# MonthCalendar Control. It is referred as a graphical interface that is widely used to modify and set date information based on your requirements. It is slightly different than DateTimePicker control in which you can select range of dates. DateTimePicker allows you to set both date and time, however, MonthCalendar control gives you a permission to select date only, but it gives you flexibility of selecting range of dates. Let's dive in and explore what this control does and what are its main applications.
C# MonthCalendar Control
- C# MonthCalendar Control is known as graphical interface that is used to modify and select range of date information for required application.
- In order to create C# MonthCalendar control, open the windows form application and go to Toolbar appearing on the left side.
- Find the MonthCalendar control, drag and drop it over the Form.
- You can play with it and move it around over the Form with the help of mouse.
- There is another way of creating the MonthCalendar control. Just double click on the MonthCalendar control, it will automatically place the MonthCalendar control on the Form.
MonthCalendar Control Properties
- In order to set the MonthCalendar control properties, just right click on the MonthCalendar control and go to properties.
- Properties window will appear on the right side of the windows form application.
- MonthCalendar control comes with different useful properties including, name, location, font, forecolor, back color, margin, MaximumDate, MaximumSize etc. Let’s discuss them one by one. Following window will appear as click on the properties.
Name
- Name property defines the specific name of the control that is used to access it in the code. In the figure above, MonthCalendar control name is monthCalendar1.
BackColor and ForeColor
- BackColor property is used to change the background color of the MonthCalendar control.
- ForeColor is used to display text within a month.
SelectionRange and SelectionStart
- SelectionRange is widely used property which defines the selected range of dates in the control.
- SelectionStart property specifies the start date of the selected range of dates.
FirstDayOfWeek and ShowTodayCircle
- FirstDayOfWeek property gives you an option to start week in the application with your preferred day. By default Sunday is selected as the start of the week and Saturday is considered as the last day of the week.
- ShowTodayCircle property is used to set the circle around current date. By default the value of this property is set as true. You can set it to false if you want to remove the circle around the current date.
ShowDate, MinDate and MaxDate
- ShowDate property displays the current date at the bottom of the calendar if its value is set as true. Setting the value to false will disappear the date at the bottom of the calendar.
- The maximum and minimum time period in the control is set by using two properties MaxDate and MinDate. MaxDate determines the maximum valid date for the control.
- MinDate determines the minimum valid date for the control.
- The Visual Basic version we are using shows MaxDate as 12/31/9998 and MinDate as 1/1/1753
CalendarDimensions and TodayDate
- CalendarDimensions determines the number of months in a single grid. Default dimension is set as (1,1) which will only display one month range in the grid.
- Maximum 12 month can be displayed in a single grid. And maximum dimension you can set is (4,3) which shows 12 months in four columns and three rows.
- Following figure shows two columns and two rows in the calendar grid because dimensions are set as (2,2)
- Following code can be used to set the number of months vertically and horizontally.
monthCalendar1.CalendarDimensions = new System.Drawing.Size (3,2);
- TodayDate is very useful property that determines the current date it captures from the system. Great thing is that you can select any date explicitly using TodayDate property and set it as current date.
ShowWeekNumbers
- ShowWeekNumbers property allows you to display week number on the calendar. By default this property value is set as false.
- Set this value as true if you want to display number of weeks in the current month of the calendar.
- In the following figure, 9,10,11,12,13,14 are the week numbers of the calendar year.
BoldedDates and Dock
- BoldedDates is an important property that is used to highlight some dates on the calendar.
- In order to create bold dates, right click on the calendar and go to properties.
- Find the BoldedDates property and click the ellipsis of its field.
- This will allow you to open DateTime Collection Editor from where you can bold the dates of your own choice.
- You can click add in order to create date member.
- As you click add, DateTime field would appear under which you can select any date value.
- Repeat the same process again if you want to bold more dates on the calendar. Following figure shows how you can bold some dates.
- In order to create bolded dates in the code, you must create DateTime object. Add following code if you want to create specific dates in bold numbers.
DateTime myVacation1 = new DateTime(2018, 3, 16);
DateTime myVacation2 = new DateTime(2018, 3, 17);
monthCalendar1.AddBoldedDate(myVacation1);
monthCalendar1.AddBoldedDate(myVacation2);
- Dock property determines the location on the calendar on the main Form. It comes with different values including top, bottom, right, left, fill and none.
Example 1
- Following example shows two month of the calendar year in the MonthCalendar Control.
- This example shows how you can bold some specific dates of your own choice and how you can make use of properties like MaxDate, MinDate, MaxSelectionCount, ShowToday, ShowTodayCircle etc.
- The DateSelected event is also used and its output is displayed on the form.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication26
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
DateTime myVacation1 = new DateTime(2018, 3, 16);
DateTime myVacation2 = new DateTime(2018, 3, 17);
monthCalendar1.AddBoldedDate(myVacation1);
monthCalendar1.AddBoldedDate(myVacation2);
this.monthCalendar1.CalendarDimensions = new System.Drawing.Size(2, 1);
this.monthCalendar1.FirstDayOfWeek = System.Windows.Forms.Day.Tuesday;
this.monthCalendar1.MaxDate = new System.DateTime(2028, 12, 31, 0, 0, 0, 0);
this.monthCalendar1.MinDate = new System.DateTime(1990, 1, 1, 0, 0, 0, 0);
this.monthCalendar1.MaxSelectionCount = 20;
this.monthCalendar1.ShowToday = true;
this.monthCalendar1.ShowTodayCircle = true;
this.monthCalendar1.ShowWeekNumbers = true;
this.monthCalendar1.DateSelected += new System.Windows.Forms.DateRangeEventHandler(this.monthCalendar1_DateSelected);
}
private void monthCalendar1_DateSelected(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
// Show the start and end dates in the text box.
this.txtLabel.Text = "Date Selected: Start = " +
e.Start.ToShortDateString() + " : End = " + e.End.ToShortDateString();
}
- And in Visual Studio Windows Form Application code will appear like below.
That's all for today. I hope you have enjoyed the article. However, if you need help, you can ask me in the comment section below. I'd love to help you in this regard according to best of my expertise. Stay Tuned!
C# LinkLabel Control
Hey Everyone! Hope you all are doing great and enjoying your lives. My job is to keep you updated with useful information that helps you excel in your relevant field. Today, I am going to give the details on the
C# Linklabel Control. This control allows you to display a hyperlink. It exhibits all the properties given by C# Label Control but it is explicitly used for displaying useful information on the hyperlink. I'll try to cover each and every aspect related to C# Linklabel Control so you don't need to go anywhere for finding the information regarding this control. Let's hop on the board and dive in the details of this control and explore its properties step by step.
C# LinkLabel Control
- C# Linklabel Control is used to display hyperlink to provide useful information.
- In order to create C# Linklabel control, open the windows form application and go to Toolbar appearing on the left side.
- Find the Linklabel control, drag and drop it over the Form.
- You can play with it and move it around over the Form with the help of mouse.
- There is another way of creating the Linklabel control. Just double click on the Linklabel control, it will automatically place the Linklabel control on the Form.
Linklabel Control Properties
- In order to set the Linklabel control properties, just right click on the Linklabel control and go to properties.
- Properties window will appear on the right side of the windows form application.
- Linklabel control comes with different useful properties including, name, autosize, text, size, font, fontcolor, back color etc. Let's discuss them one by one. Following window will appear as click on the properties.
Name and Text Properties
- Name property defines the specific name of the control that is used to access it in the code. In the figure above, Linklabel control name is linkLabel1.
- Similarly, text property is used to display the descriptive text on the link. You can go to properties and change the name manually or you can change it in a code as well.
- Following code can be used to change the text of the Linklabel Control.
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
linkLabel1.Text = "this is label one";
}
BackColor, BorderStyle, ForeColor Properties
- BackColor property is used to change the background color of the linklable control.
- BorderStyle is used to give linklable control a specific border style around the link text. It comes with two border styles including FixedSingle, Fixed 3D.
- ForeColor is used to change the forecolor of the linklabel control.
Font, AutoSize and TextAlign Properties
- Font property shows the font style of the text that can be used in linklabel control. When you go to properties, and click on Font property, it shows different font styles, size and
- AutoSize property is used to change the size of the linklable control. By default the value of AutoSize property is true, when it is true, you can not change the size of the linklable. When it is set to false, you can change the size of linklabel.
- Similarly, TextAlign property is used to align the linklabel text in the linklable control. It comes with 9 different options to align the text at different place on the linklabel control.
Image and ImageAlign Properties
- Image property is used to set the background of the linklabel control as an image.
- Similarly, ImganAlign property is used to align the image on the background of the linklabel control.
Color Properties
- LinkColor property shows the color of the link in linklabel control.
- LinkVisited property comes with two states true and false. When it is false, color of the link won't be changed once the link is visited. When it is set true, the color of the link will change once the link is visited.
- VisitedLinkColor property shows the color of the visited link. By default purple color is set to the VisitedLinkColor property.
- ActiveLinkColor property represents the color when you put the cursor on the link and click. The color appears before you fully clicked the link is ActiveLinkColor.
Example 1
- We are going to build a program which will allow the linklabel to open some website.
- In order to do this, open the windows form application and drag and drop the linklabel from the Toolbar to Form.
- Double click on the linklabel, following figure will appear.
- Now add "using System.Diagnostics" in the code just like the shown in the figure below.
- Now add following code in your application. When you run the application, and click on the link, it will allow the link to open the google website.
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start("www.google.com");
}
That's all for today. Thanks for reading the article. We always love when you keep coming back for what we have to offer. If you have any question you can ask me in the comment section below. I'd love to help you according to best of my expertise. Stay Tuned!
C# ListView Control
Hi Guys! Hope you are doing great. Our mission is to give you valuable knowledge related to your field so you keep coming back for what we have to offer. Today, I am going to unlock the details on the
C# ListView Control. It displays useful information about list of items by using various views available in the control. You can also have a look at LinkLabel and DateTimePicker that I have discussed previously. I'll try to cover every aspect related to ListView Control so you get a clear idea about this control and you don't need to go anywhere else for finding the information regarding this control. Let's get started.
C# ListView Control
- C# ListView Control is used to display list of items by using various views available in the control.
- It is very useful in developing the applications where you want the data to be arranged in the form of list.
- Creating a ListView Control in Windows Form Application is very easy.
- Simply open the windows form application and drag the listview control from the ToolBar to Form.
- You can also create it by double clicking the listview control on the ToolBar, it will automatically place the listview control on the Form. Once you create the listview control it will look like the figure below.
- You can change its location with the help of mouse.
- Once you click on the little arrow available on the top right corner, it will appear like the figure below.
- Here you can see the ListView Tasks from where you can add items, columns, groups in the list and can change the view of the list that comes with different view options including largeicon, smallicon, list, title.
ListView Properties
- LlistView control comes with lots of different properties which you can modify manually.
- In order to open the properties window, right click on the listview control on the Form and go to properties windows.
- Once you open the properties windows, it will appear like the figure below which comes with different available properties.
Name
- Go to properties window and find property "Name" which specifies the unique name of the control which is used to access it in the the main code.
Location and Size Properties
- Location property represents the starting point of the listview control on the main Form. In other words, it represents the coordinates of the upper left corner of the control relative to the upper left corner of the container.
- Size property defines the size of listview control on the main Form. You can put the width and length on the size property or you can increase the size of the control by clicking the lower right corner of the control and expanding it towards right side.
ForeColor and BackColor Propeties
- ForeColor represents the forecolor of the listview control on the main Form.
- BackColor property represents the background color of the listview control.
- You can change both forecolor and backcolor manually by simply going to the properties window by right clicking on the listview control or you can change them by the help of code. Following lines can be used to change fore and back color in the code.
listView1.BackColor = Color.Brown;
listView1.ForeColor = Color.Blue;
View, GridLines, FullRowSelect Properties
- View property comes with 5 options to view the data on the list. FullRowSelect Property allows the cursor to select all add appearing in single row.
- Similarly, if you set GridProperty property as true, it will put the grid lines on the listview control. Following lines can be used to access these properties in the code.
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
Items and CheckBoxes Properties
- Items property is very useful in this control that allows you to add items one by one. You can add items manually through this control but better way is using proper code to add items in the listview control.
- You can use these lines to add items in the code
ListViewItem lv1 = new ListViewItem("Adnan Aqeel");
lv1.SubItems.Add("123 main street");
lv1.SubItems.Add("25");
listView1.Items.Add(lv1);
- First we create three columns naming name, address and age and set the view to details. Then we add above lines in the main code by double clicking the listview control.
- CheckBoxes property allows you to add checkbox in the listed item. By default checkboxes property is false, set this property as true in order to add checkboxes of items in the control.
LabelEdit and HoverSelection Properties
- LabelEdit is very handy as it allows you to change the text of the items available in the list.
- Set this property as true in order to change the text of the items manually.
- However, you can also change text of the items dynamically in the code.
- HoverSelection property is used to make the item selected when someone hover the mouse on it.
- Set this property true in order to make the item selected over hovering the mouse over it.
HotTracking and Alignment Properties
- HotTracking property allows you to underline the text of the item and make it prominent when someone hovers mouse over the item in the list. Set this property as true in order to make this property useful.
- Alignment property is very useful that allows you to align the items in the list properly. It comes with four options including default, left, top, SnapToGird.
Columns and Groups Properties
- Columns property is very important property of the control that allows you to add the columns in the list. This property becomes handy when you are using the Details view of the control.
- Groups property allows you to distinguish the classes of items distinctively.
How to Add Columns in the ListView Control
Example 1
- Let's create a code for which we add items on the list step by step by the add button, then we remove the selected data from the delete button and then clear all data from the clear button in the windows form application.
- When we add one panel, three buttons, three textboxes, three labels and one listview on the main form, it will look like a figure below.
- Following is the code to run this application to add items in the list step by step and remove it or clear it completely.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication20
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnAddRecord_Click(object sender, EventArgs e)
{
ListViewItem lv1 = new ListViewItem(txtStudentName.Text);
lv1.SubItems.Add(txtFatherName.Text);
lv1.SubItems.Add(txtRegistrationNo.Text);
lvRecord.Items.Add(lv1);
}
private void btnDeleteSelected_Click(object sender, EventArgs e)
{
lvRecord.Items.Remove(lvRecord.SelectedItems[0]);
}
private void btnClearAll_Click(object sender, EventArgs e)
{
lvRecord.Items.Clear();
}
}
}
- Following figure shows the code in Visual Studio.
- Here's a short video in which I have shown How to use C# ListView Control:
That's all for today. I hope you have enjoyed the article and got to know the features of listview control. We always love when you visit our website to resolve your issues related to engineering. However, if still you feel any doubt or have any question you can ask me in the comment section below. I'd love to help you according to best of my expertise. Stay Tuned!