-
Notifications
You must be signed in to change notification settings - Fork 0
/
csharp programming notes.txt
10505 lines (8520 loc) · 453 KB
/
csharp programming notes.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=============================
Introduction to Pointers
=============================
Pointers
Every variable is a memory location, which has its address defined.
That address can be accessed using the ampersand (&) operator (also called the address-of operator), which denotes an address in memory.
For example:
#include <iostream>
using namespace std;
int main()
{
int score = 5;
cout << &score << endl;
return 0;
}
This outputs the memory address, which stores the variable score.
Pointers
A pointer is a variable, with the address of another variable as its value.
In C++, pointers help make certain tasks easier to perform. Other tasks, such as dynamic memory allocation, cannot be performed without using pointers.
All pointers share the same data type - a long hexadecimal number that represents a memory address.
The only difference between pointers of different data types is the data type of the variable that the pointer points to.
Pointers
A pointer is a variable, and like any other variable, it must be declared before you can work with it.
The asterisk sign is used to declare a pointer (the same asterisk that you use for multiplication), however, in this statement the asterisk is being used to designate a variable as a pointer.
Following are valid pointer declarations:
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch; // pointer to a character
CPP
Just like with variables, we give the pointers a name and define the type, to which the pointer points to.
The asterisk sign can be placed next to the data type, or the variable name, or in the middle.
Using Pointers
Here, we assign the address of a variable to the pointer.
#include <iostream>
using namespace std;
int main()
{
int score = 5;
int *scorePtr;
scorePtr = &score;
cout << scorePtr << endl;
return 0;
}
The code above declares a pointer to an integer called scorePtr, and assigns to it the memory location of the score variable using the ampersand (address-of) operator.
Now, scorePtr's value is the memory location of score.
=============================
More on Pointers
=============================
Pointer Operations
There are two operators for pointers:
Address-of operator (&): returns the memory address of its operand.
Contents-of (or dereference) operator (*): returns the value of the variable located at the address specified by its operand.
For example:
#include <iostream>
using namespace std;
int main()
{
int var = 50;
int *p;
p = &var;
cout << var << endl;
// Outputs 50 (the value of var)
cout << p << endl;
// Outputs 0x29fee8 (var's memory location)
cout << *p << endl;
/* Outputs 50 (the value of the variable
stored in the pointer p) */
return 0;
}
The asterisk (*) is used in declaring a pointer for the simple purpose of indicating that it is a pointer (The asterisk is part of its type compound specifier). Don't confuse this with the dereference operator, which is used to obtain the value located at the specified address. They are simply two different things represented with the same sign.
Dereferencing
The dereference operator (*) is basically an alias for the variable the pointer points to.
For example:
int x = 5;
int *p = &x;
x = x + 4;
x = *p + 4;
*p = *p + 4;
CPP
All three of the preceding statements are equivalent, and return the same result. We can access the variable by dereferencing the variable's pointer.
As p is pointing to the variable x, dereferencing the pointer (*p) is representing exactly the same as the variable x.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
TABLE OF CONTENTS:
::Basic Concepts::
1.1 What is C#?
2.1 Variables
3.1 Your First C# Program
4.1 Printing Text
5.1 Getting User Input
6.1 Comments
7.1 The var Keyword
8.1 Constants
9.1 Arithmetic Operators
10.1 Assignment & Increment Operators
::Conditionals and Loops::
13.1 The if-else Statement
14.1 The switch Statement
15.1 The while Loop
16.1 The for Loop
17.1 The do-while Loop
18.1 break and continue
19.1 Logical Operators
20.1 The Conditional Operator
21.1 Basic Calculator
::Methods::
24.1 Introduction to Methods
25.1 Method Parameters
26.1 Multiple Parameters
27.1 Optional & Named Arguments
28.1 Passing Arguments
29.1 Method Overloading
30.1 Recursion
31.1 Making a Pyramid
::Classes & Objects::
34.1 Classes & Objects
35.1 Value & Reference Types
36.1 Class Example
37.1 Encapsulation
38.1 Constructors
39.1 Properties
::Arrays and Strings::
42.1 Arrays
43.1 Using Arrays in Loops
44.1 Multidimensional Arrays
45.1 Jagged Arrays
46.1 Array Properties & Methods
47.1 Working with Strings
::More on Classes::
50.1 Destructors
51.1 Static Members
52.1 Static Classes
53.1 this & readonly
54.1 Indexers
55.1 Operator Overloading
::Inheritance & Polymorphism::
58.1 Inheritance
59.1 Protected Members
60.1 Derived Class Constructor & Destructor
61.1 Polymorphism
62.1 Abstract Classes
63.1 Interfaces
64.1 Nested Classes
65.1 Namespaces
::Structs, Enums, Exceptions & Files::
68.1 Structs
69.1 Enums
70.1 Exception Handling
71.1 Working with Files
::Generics::
74.1 Generic Methods
75.1 Generic Classes
76.1 Collections
77.1 Lists and BitArray
78.1 Stack & Queue
79.1 Dictionary & HashSet
Check for Try it yourself before Basic Concepts -> Printing Text. Delegates + -=Typecasting=- convert one datatype to another. -=Delegate=- function pointer; delegates contains the reference to several methods and call them when needed. So, you create numbers of methods as you need and attach it to delegates. At runtime, an event gets fired and delegates dynamically call the function and show the result. -=Callback Function=- call to another function await another function to finish & alert calling. -=Nested For Loop=- outer loop creates rectangle, inner loop fills it. -=index++ (postfix (increment afterwards))=- https://www.cprogramming.com/tutorial/function-pointers.html
=============================
=============================
C# Basics
=============================
=============================
=============================
1.1 What is C#?
=============================
Welcome to C#
C# is an elegant object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework.
You can use C# to create Windows applications, Web services, mobile applications, client-server applications, database applications, and much, much more.
The .NET Framework
The .NET Framework consists of the Common Language Runtime (CLR) and the .NET Framework class library.
The CLR is the foundation of the .NET Framework. It manages code at execution time, providing core services such as memory management, code accuracy, and many other aspects of your code.
The class library is a collection of classes, interfaces, and value types that enable you to accomplish a range of common programming tasks, such as data collection, file access, and working with text.
C# programs use the .NET Framework class library extensively to do common tasks and provide various functionalities.
These concepts might seem complex, but for now just remember that applications written in C# use the .NET Framework and its components.
=============================
2.1 Variables
=============================
Programs typically use data to perform tasks.
Creating a variable reserves a memory location, or a space in memory, for storing values. It is called variable because the information stored in that location can be changed when the program is running.
To use a variable, it must first be declared by specifying the name and data type.
A variable name, also called an identifier, can contain letters, numbers and the underscore character (_) and must start with a letter or underscore.
Although the name of a variable can be any set of letters and numbers, the best identifier is descriptive of the data it will contain. This is very important in order to create clear, understandable and readable code!
For example, firstName and lastName are good descriptive variable names, while abc and xyz are not.
Variable Types
A data type defines the information that can be stored in a variable, the size of needed memory and the operations that can be performed with the variable.
For example, to store an integer value (a whole number) in a variable, use the int keyword:
int myAge;
CS
The code above declares a variable named myAge of type integer.
A line of code that completes an action is called a statement. Each statement in C# must end with a semicolon.
You can assign the value of a variable when you declare it:
int myAge = 18;
CS
or later in your code:
int myAge;
myAge = 18;
CS
Remember that you need to declare the variable before using it.
Built-in Data Types
There are a number of built-in data types in C#. The most common are:
int - integer.
float - floating point number.
double - double-precision version of float.
char - a single character.
bool - Boolean that can have only one of two values: True or False.
string - a sequence of characters.
The statements below use C# data types:
int x = 42;
double pi = 3.14;
char y = 'Z';
bool isOnline = true;
string firstName = "David";
CS
Note that char values are assigned using single quotes and string values require double quotes.
You will learn how to perform different operations with variables in the upcoming lessons!
=============================
3.1 Your First C# program
=============================
You can run, save, and share your C# codes on our Code Playground, without installing any additional software.
Reference this lesson if you need to install the software on your computer.
To create a C# program, you need to install an integrated development environment (IDE) with coding and debugging tools.
We will be using Visual Studio Community Edition, which is available to download for free.
After installing it, choose the default configuration.
Next, click File->New->Project and then choose Console Application as shown below:contentImageEnter a name for your Project and click OK.
Console application uses a text-only interface. We chose this type of application to focus on learning the fundamentals of C#.
Your First C# Program
Visual Studio will automatically generate some code for your project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
}
}
}
CS
You will learn what each of the statements does in the upcoming lessons.
For now, remember that every C# console application must contain a method (a function) named Main. Main is the starting point of every application, i.e. the point where our program starts execution from.
We will learn about classes, methods, arguments, and namespaces in the upcoming lessons.
Your First C# Program
To run your program, press Ctrl+F5. You will see the following screen:contentImageThis is a console window. As we did not have any statements in our Main method, the program just produces a general message. Pressing any key will close the console.
Congratulations, you just created your first C# program.
=============================
4.1 Printing Text
=============================
Displaying Output
Most applications require some input from the user and give output as a result.
To display text to the console window you use the Console.Write or Console.WriteLine methods. The difference between these two is that Console.WriteLine is followed by a line terminator, which moves the cursor to the next line after the text output.
The program below will display Hello World! to the console window:
Note the parentheses after the WriteLine method. This is the way to pass data, or arguments, to methods. In our case WriteLine is the method and we pass "Hello World!" to it as an argument. String arguments must be enclosed in quotation marks.
Displaying Output
We can display variable values to the console window:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int x = 89;
Console.WriteLine(x);
}
}
}
To display a formatted string, use the following syntax:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int x = 10;
double y = 20;
Console.WriteLine("x = {0}; y = {1}", x, y);
}
}
}
As you can see, the value of x replaced {0} and the value of y replaced {1}.
You can have as many variable placeholders as you need. (i.e.: {3}, {4}, etc.).
icon
Your First Program
C# is cool! Let everyone know about it!
=============================
5.1 Getting User Input
=============================
User Input
You can also prompt the user to enter data and then use the Console.ReadLine method to assign the input to a string variable.
The following example asks the user for a name and then displays a message that includes the input:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
string yourName;
Console.WriteLine("What is your name?");
yourName = Console.ReadLine();
Console.WriteLine("Hello {0}", yourName);
}
}
}
The Console.ReadLine method waits for user input and then assigns it to the variable. The next statement displays a formatted string containing Hello with the user input. For example, if you enter David, the output will be Hello David.
Note the empty parentheses in the ReadLine method. This means that it does not take any arguments.
User Input
The Console.ReadLine() method returns a string value.
If you are expecting another type of value (such as int or double), the entered data must be converted to that type.
This can be done using the Convert.ToXXX methods, where XXX is the .NET name of the type that we want to convert to. For example, methods include Convert.ToDouble and Convert.ToBoolean.
For integer conversion, there are three alternatives available based on the bit size of the integer: Convert.ToInt16, Convert.ToInt32 and Convert.ToInt64. The default int type in C# is 32-bit.
Let’s create a program that takes an integer as input and displays it in a message:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You are {0} years old", age);
}
}
}
If, in the program above, a non-integer value is entered (for example, letters), the Convert will fail and cause an error.
=============================
6.1 Comments
=============================
Comments are explanatory statements that you can include in a program to benefit the reader of your code.
The compiler ignores everything that appears in the comment, so none of that information affects the result.
A comment beginning with two slashes (//) is called a single-line comment. The slashes tell the compiler to ignore everything that follows, until the end of the line.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
// Prints Hello
Console.WriteLine("Hello");
}
}
}
When you run this code, Hello will be displayed to the screen. The // Prints Hello line is a comment and will not appear as output.
Multi-Line Comments
Comments that require multiple lines begin with /* and end with */ at the end of the comment block.
You can place them on the same line or insert one or more lines between them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
/* Some long
comment text
*/
int x = 42;
Console.WriteLine(x);
}
}
}
Adding comments to your code is good programming practice. It facilitates a clear understanding of the code for you and for others who read it.
=============================
7.1 The var Keyword
=============================
A variable can be explicitly declared with its type before it is used.
Alternatively, C# provides a handy function to enable the compiler to determine the type of the variable automatically based on the expression it is assigned to.
The var keyword is used for those scenarios:
var num = 15;
CS
The code above makes the compiler determine the type of the variable. Since the value assigned to the variable is an integer, the variable will be declared as an integer automatically.
The var Keyword
Variables declared using the var keyword are called implicitly typed variables.
Implicitly typed variables must be initialized with a value.
For example, the following program will cause an error:
var num;
num = 42;
CS
Although it is easy and convenient to declare variables using the var keyword, overuse can harm the readability of your code. Best practice is to explicitly declare variables.
=============================
8.1 Constants
=============================
Constants store a value that cannot be changed from their initial assignment.
To declare a constant, use the const modifier.
For example:
const double PI = 3.14;
CS
The value of const PI cannot be changed during program execution.
For example, an assignment statement later in the program will cause an error:
const double PI = 3.14;
PI = 8; //error
CS
Constants must be initialized with a value when declared.
=============================
9.1 Arithmetic Operators
=============================
An operator is a symbol that performs mathematical or logical manipulations.
Arithmetic Operators
C# supports the following arithmetic operators:
Operator Symbol Form
Addition + x+y
Subtraction - x-y
Multiplication * x*y
Division / x/y
Modulus % x%y
Division
The division operator (/) divides the first operand by the second. If the operands are both integers, any remainder is dropped in order to return an integer value.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int x = 10 / 4;
Console.WriteLine(x);
}
}
}
Division by 0 is undefined and will crash your program.
Modulus
The modulus operator (%) is informally known as the remainder operator because it returns the remainder of an integer division.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int x = 25 % 7;
Console.WriteLine(x);
}
}
}
Operator Precedence
Operator precedence determines the grouping of terms in an expression, which affects how an expression is evaluated. Certain operators take higher precedence over others; for example, the multiplication operator has higher precedence than the addition operator.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int x = 4+3*2;
Console.WriteLine(x);
}
}
}
The program evaluates 3*2 first, and then adds the result to 4.
As in mathematics, using parentheses alters operator precedence.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int x = (4 + 3) *2;
Console.WriteLine(x);
}
}
}
The operations within parentheses are performed first. If there are parenthetical expressions nested within one another, the expression within the innermost parentheses is evaluated first.
If none of the expressions are in parentheses, multiplicative (multiplication, division, modulus) operators will be evaluated before additive (addition, subtraction) operators. Operators of equal precedence are evaluated from left to right.
=============================
10.1 Assignment & Increment Operators
=============================
The = assignment operator assigns the value on the right side of the operator to the variable on the left side.
C# also provides compound assignment operators that perform an operation and an assignment in one statement.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int x = 42;
x += 2; // equivalent to x = x + 2
Console.WriteLine(x);
x -= 6; // equivalent to x = x - 6
Console.WriteLine(x);
}
}
}
Assignment Operators
The same shorthand syntax applies to the multiplication, division, and modulus operators.
x *= 8; // equivalent to x = x * 8
x /= 5; // equivalent to x = x / 5
x %= 2; // equivalent to x = x % 2
CS
The same shorthand syntax applies to the multiplication, division, and modulus operators.
Increment Operator
The increment operator is used to increase an integer's value by one, and is a commonly used C# operator.
x++; //equivalent to x = x + 1
CS
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int x = 10;
x++;
Console.WriteLine(x);
}
}
}
The increment operator is used to increase an integer's value by one.
Prefix & Postfix Forms
The increment operator has two forms, prefix and postfix
++x; //prefix
x++; //postfix
CS
Prefix increments the value, and then proceeds with the expression.
Postfix evaluates the expression and then performs the incrementing.
Prefix example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int x = 3;
int y = ++x;
Console.WriteLine(x+" "+y);
}
}
}
Postfix example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int x = 3;
int y = x++;
Console.WriteLine(x+" "+y);
}
}
}
The prefix example increments the value of x, and then assigns it to y.
The postfix example assigns the value of x to y, and then increments x.
Decrement Operator
The decrement operator (--) works in much the same way as the increment operator, but instead of increasing the value, it decreases it by one.
--x; // prefix
x--; // postfix
CS
The decrement operator (--) works in much the same way as the increment operator.
=============================
=============================
Conditionals and Loops
=============================
=============================
=============================
13.1 The if-else Statement
=============================
The if statement is a conditional statement that executes a block of code when a condition is true.
The general form of the if statement is:
if (condition)
{
// Execute this code when condition is true
}
CS
The condition can be any expression that returns true or false.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int x = 8;
int y = 3;
if (x > y)
{
Console.WriteLine("x is greater than y");
}
}
}
}
The code above will evaluate the condition x > y. If it is true, the code inside the if block will execute.
When only one line of code is in the if block, the curly braces can be omitted.
For example:
if (x > y)
Console.WriteLine("x is greater than y");
Relational Operators
Operator Description Example
>= Greater than or equal to 7>=4 True
<= Less than or equal to 7<=4 False
== Equal to 7==4 False
!= Not equal to 7!=4 True
Use relational operators to evaluate conditions. In addition to the less than (<) and greater than (>) operators, the following operators are available:contentImage Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int a=7, b=7;
if (a == b) {
Console.WriteLine("Equal");
}
}
}
}
The else Clause
An optional else clause can be specified to execute a block of code when the condition in the if statement evaluates to false.
Syntax:
if (condition)
{
//statements
}
else
{
//statements
}
CS
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int mark = 85;
if (mark < 50)
{
Console.WriteLine("You failed.");
}
else
{
Console.WriteLine("You passed.");
}
}
}
}
Nested if Statements
You can also include, or nest, if statements within another if statement.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int mark = 100;
if (mark >= 50) {
Console.WriteLine("You passed.");
if (mark == 100) {
Console.WriteLine("Perfect!");
}
}
else {
Console.WriteLine("You failed.");
}
}
}
}
You can nest an unlimited number of if-else statements.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int age = 17;
if (age > 14) {
if(age > 18) {
Console.WriteLine("Adult");
}
else {
Console.WriteLine("Teenager");
}
}
else {
if (age > 0) {
Console.WriteLine("Child");
}
else {
Console.WriteLine("Something's wrong");
}
}
}
}
}
Remember that all else clauses must have corresponding if statements.
The if-else if Statement
The if-else if statement can be used to decide among three or more actions.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int x = 33;
if (x == 8) {
Console.WriteLine("Value of x is 8");
}
else if (x == 18) {
Console.WriteLine("Value of x is 18");
}
else if (x == 33) {
Console.WriteLine("Value of x is 33");
}
else {
Console.WriteLine("No match");
}
}
}
}
Remember, that an if can have zero or more else if's and they must come before the last else, which is optional.
Once an else if succeeds, none of the remaining else if's or else clause will be tested.
=============================
14.1 The switch Statement
=============================
The switch statement provides a more elegant way to test a variable for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each switch case.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;