├── LICENSE
└── README.md
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # C# Cheat Sheet - ConstructG.com
2 |
3 | **Version:** 1.0.1
4 |
5 | **Framework Version:** .NET Core 3.1.9 or later.
6 |
7 | **Language Version:** C# 8.0 or later.
8 |
9 | ## Table Of Contents (TOC)
10 |
11 | - [C# Cheat Sheet](#c-cheat-sheet)
12 | - [About](#about)
13 | - [C# Introduction](#c-introduction)
14 | - [What is C#?](#what-is-c)
15 | - [What Is C# Used For?](#what-is-c-used-for)
16 | - [C# Keywords](#c-keywords)
17 | - [Reserved Keywords](#reserved-keywords)
18 | - [Contextual Keywords](#contextual-keywords)
19 | - [C# Special Characters](#c-special-characters)
20 | - [C# Preprocessor Directives](#c-preprocessor-directives)
21 | - [General Syntax](#general-syntax)
22 | - [Comments](#comments)
23 | - [C# Hello World Console Application](#c-hello-world-console-application)
24 | - [C# Variables](#c-variables)
25 | - [C# Naming Conventions](#c-naming-conventions)
26 | - [Terminology](#terminology)
27 | - [Summary Table](#summary-table)
28 | - [C# Data Types](#c-data-types)
29 | - [Value Types](#value-types)
30 | - [Simple Data Types](#simple-data-types)
31 | - [Bytes](#bytes)
32 | - [Unsigned Integers](#unsigned-integers)
33 | - [Signed Integers](#signed-integers)
34 | - [Floating-Point Types](#floating-point-types)
35 | - [Unicode Characters](#unicode-characters)
36 | - [Booleans](#booleans)
37 | - [Enum Types](#enum-types)
38 | - [Structure Types](#structure-types)
39 | - [Tuple Types](#tuple-types)
40 | - [Nullable Value Types](#nullable-value-types)
41 | - [Reference Types](#reference-types)
42 | - [Built-In Reference Types](#built-in-reference-types)
43 | - [Object Types](#object-types)
44 | - [String Types](#string-types)
45 | - [Delegate Types](#delegate-types)
46 | - [Interface Types](#interface-types)
47 | - [Nullable Reference Types](#nullable-reference-types)
48 | - [Array Types](#array-types)
49 | - [Array Of Simple Types](#array-of-simple-types)
50 | - [Jagged Arrays](#jagged-arrays)
51 | - [Array Properties & Methods](#array-properties--methods)
52 | - [Type Casting](#type-casting)
53 | - [Implicit Casting](#implicit-casting)
54 | - [Explicit Casting](#explicit-casting)
55 | - [Type Conversion Methods](#type-conversion-methods)
56 | - [Operators](#operators)
57 | - [Arithmetic Operators](#arithmetic-operators)
58 | - [Combined Assignment Operators](#combined-assignment-operators)
59 | - [Increment and Decrement Operators](#increment-and-decrement-operators)
60 | - [Comparison Operators](#comparison-operators)
61 | - [Logical Operators](#logical-operators)
62 | - [Bitwise Operators](#bitwise-operators)
63 | - [Operator Precedents](#operator-precedents)
64 | - [Statements](#statements)
65 | - [Conditions](#conditions)
66 | - [**```if```**...**```else if```**...**```else```**](#ifelse-ifelse)
67 | - [**```switch```** Case](#switch-case)
68 | - [Loops](#loops)
69 | - [**```while```** Loop](#while-loop)
70 | - [**```do```**...**```while```** Loop](#dowhile-loop)
71 | - [**```for```** Loop](#for-loop)
72 | - [**```foreach```** Loop](#foreach-loop)
73 | - [**```goto```** Statement](#goto-statement)
74 | - [**```return```** Statement](#return-statement)
75 | - [**```yield```** Statement](#yield-statement)
76 | - [**```checked```** and **```unchecked```** Statements](#checked-and-unchecked-statements)
77 | - [**```lock```** Statement](#lock-statement)
78 | - [**```using```** Statement](#using-statement)
79 | - [Exception Handling](#exception-handling)
80 | - [Classes & Objects](#classes--objects)
81 | - [Members](#members)
82 | - [Constructors](#constructors)
83 | - [The ```this``` Keyword](#the-this-keyword)
84 | - [Garbage Collector](#garbage-collector)
85 | - [Destructors / Finalizers](#destructors--finalizers)
86 | - [Object-Oriented Programming (OOP)](#object-oriented-programming-oop)
87 | - [Encapsulation / Access Levels](#encapsulation--access-levels)
88 | - [Inheritance](#inheritance)
89 | - [Polymorphism / Redefining Members](#polymorphism--redefining-members)
90 | - [Static](#static)
91 | - [Properties](#properties)
92 | - [Indexers](#indexers)
93 | - [Abstraction](#abstraction)
94 | - [Abstract Classes & Methods](#abstract-classes--methods)
95 | - [Interfaces](#interfaces)
96 | - [Namespaces](#namespaces)
97 | - [Operator Overloading](#operator-overloading)
98 | - [Delegates](#delegates)
99 | - [Anonymous Methods](#anonymous-methods)
100 | - [Lambda Expressions](#lambda-expressions)
101 | - [Events](#events)
102 | - [Generics](#generics)
103 | - [Generic Collections](#generic-collections)
104 | - [List](#list)
105 | - [SortedList](#sortedlist)
106 | - [BitArray](#bitarray)
107 | - [Stack](#stack)
108 | - [Queue](#queue)
109 | - [Dictionary](#dictionary)
110 | - [HashSet](#hashset)
111 | - [Constants](#constants)
112 | - [The ```const``` Keyword](#the-const-keyword)
113 | - [The ```readonly``` Keyword](#the-readonly-keyword)
114 | - [Asynchronous Methods](#asynchronous-methods)
115 | - [Working With Files](#working-with-files)
116 | - [Language-Integrated Query (LINQ)](#language-integrated-query-linq)
117 | - [Attributes](#attributes)
118 | - [Predefined Attributes](#predefined-attributes)
119 | - [Custom Attributes](#custom-attributes)
120 | - [Extension Methods](#extension-methods)
121 | - [References](#references)
122 | - [Credits](#credits)
123 |
124 | ---
125 |
126 | ## About
127 |
128 | - The objective of this C# cheat sheet is to provide a general overview.
129 | - The HTML version of this document is hosted on: https://constructg.com/csharp-cheat-sheet/
130 | - The markdown file of this sheet is hosted on [GitHub](https://github.com/LabinatorSolutions/csharp-cheat-sheet).
131 | - Contributions, bug fixes, additions, and improvements will be much appreciated.
132 | - Prepared by [ConstructG.com](https://constructg.com/). ConstructG is an online game development academy.
133 |
134 | ## C# Introduction
135 |
136 | ### What is C#?
137 |
138 | C# is pronounced "C-Sharp". It is an object-oriented programming language created by Microsoft that runs on the .NET Framework. C# has roots from the C family, and the language is close to other popular languages like C++ and Java.
139 |
140 | ### What Is C# Used For?
141 |
142 | - Database applications
143 | - Desktop applications
144 | - Games
145 | - Mobile applications
146 | - Virtual Reality (VR) applications
147 | - Web applications
148 | - Web development
149 | - Web services
150 |
151 | **For Reference:**
152 | https://en.wikipedia.org/wiki/C_Sharp_(programming_language)
153 | https://docs.microsoft.com/en-us/dotnet/csharp/getting-started/
154 |
155 | ---
156 |
157 | ## C# Keywords
158 |
159 | ### Reserved Keywords
160 |
161 | Keywords are predefined, reserved identifiers that have special meanings to the compiler.
162 |
163 | - abstract
164 | - as
165 | - base
166 | - bool
167 | - breakbyte
168 | - case
169 | - catch
170 | - char
171 | - checked
172 | - class
173 | - const
174 | - continue
175 | - decimal
176 | - default
177 | - delegate
178 | - do
179 | - double
180 | - else
181 | - enum
182 | - event
183 | - explicit
184 | - extern
185 | - false
186 | - finally
187 | - fixed
188 | - float
189 | - for
190 | - foreach
191 | - goto
192 | - if
193 | - implicit
194 | - in
195 | - int
196 | - interface
197 | - internal
198 | - is
199 | - lock
200 | - long
201 | - namespace
202 | - new
203 | - null
204 | - object
205 | - operator
206 | - out
207 | - override
208 | - params
209 | - private
210 | - protected
211 | - public
212 | - readonly
213 | - ref
214 | - return
215 | - sbyte
216 | - sealed
217 | - short
218 | - sizeof
219 | - stackalloc
220 | - static
221 | - string
222 | - struct
223 | - switch
224 | - this
225 | - throw
226 | - true
227 | - try
228 | - typeof
229 | - uint
230 | - ulong
231 | - unchecked
232 | - unsafe
233 | - ushort
234 | - using
235 | - virtual
236 | - void
237 | - volatile
238 | - while
239 |
240 | ### Contextual Keywords
241 |
242 | A contextual keyword is used to provide a specific meaning in the code, but it is not a reserved word in C#. Some contextual keywords, such as partial and where, have special meanings in two or more contexts.
243 |
244 | - add
245 | - alias
246 | - ascending
247 | - async
248 | - await
249 | - by
250 | - descending
251 | - dynamic
252 | - equals
253 | - from
254 | - get
255 | - global
256 | - group
257 | - into
258 | - join
259 | - let
260 | - nameof
261 | - notnull
262 | - on
263 | - orderby
264 | - partial (method)
265 | - partial (type)
266 | - remove
267 | - select
268 | - set
269 | - unmanaged (generic type constraint)
270 | - value
271 | - var
272 | - when (filter condition)
273 | - where (generic type constraint)
274 | - where (query clause)
275 | - yield
276 |
277 | **Learn More:**
278 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/
279 |
280 | ---
281 |
282 | ## C# Special Characters
283 |
284 | Special characters are predefined, contextual characters that modify the program element (a literal string, an identifier, or an attribute name) to which they are prepended. C# supports the following special characters:
285 |
286 | - **@**, the verbatim identifier character.
287 | - **$**, the interpolated string character.
288 |
289 | **Learn More:**
290 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/
291 |
292 | ---
293 |
294 | ## C# Preprocessor Directives
295 |
296 | C# has the following preprocessor directives:
297 |
298 | - \#if
299 | - \#else
300 | - \#elif
301 | - \#endif
302 | - \#define
303 | - \#undef
304 | - \#warning
305 | - \#error
306 | - \#line
307 | - \#region
308 | - \#endregion
309 | - \#pragma
310 | - \#pragma warning
311 | - \#pragma checksum
312 |
313 | **Learn More:**
314 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/
315 |
316 | ---
317 |
318 | ## General Syntax
319 |
320 | - Case sensitive.
321 | - Code is typed inside code blocks **{}**
322 | - Line termination is done using semicolon **;**
323 |
324 | ---
325 |
326 | ## Comments
327 |
328 | - Single line comments are typed within two forward slashes:
329 |
330 | ```csharp
331 | // Single Line Comment
332 | ```
333 |
334 | - Multi-line comments are typed with a forward slash followed by an asterisk. It must be closed by an asterisk followed by a forward slash.
335 |
336 | ```csharp
337 | /*
338 | This is a multi-line comment.
339 | This is the second line of the comment.
340 | */
341 | ```
342 |
343 | ---
344 |
345 | ## C# Hello World Console Application
346 |
347 | ```csharp
348 | class Hello
349 | {
350 | static void Main(string[] args)
351 | {
352 | System.Console.WriteLine("Hello World!");
353 | }
354 | }
355 | ```
356 |
357 | **Note:** C# source files typically have the file extension **.cs**
358 |
359 | ---
360 |
361 | ## C# Variables
362 |
363 | **Syntax:**
364 |
365 | ```
366 | = ;
367 | ```
368 |
369 | - Variables should start with underscore and cannot contain white spaces.
370 | - It can contain numbers but should always start with a capital letter.
371 | - It cannot contain any symbols (other than underscore).
372 |
373 | **Learn More:**
374 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables
375 |
376 | ---
377 |
378 | ## C# Naming Conventions
379 |
380 | ### Terminology
381 |
382 | There are following three terminologies are used to declare C# and .NET naming standards.
383 |
384 | - **Camel Case (camelCase):** In this standard, the first letter of the word always in small letter and after that each word starts with a capital letter.
385 | - **Pascal Case (PascalCase):** In this the first letter of every word is in capital letter.
386 | - **Underscore Prefix (_underScore):** For underscore ( __ ), the word after _ use camelCase terminology.
387 |
388 | ### Summary Table
389 |
390 | | Kind | Rule |
391 | | --------------- | --------------- |
392 | | Private Field | _lowerCamelCase |
393 | | Protected Field | UpperCamelCase |
394 | | Internal Field | UpperCamelCase |
395 | | Constant | UpperCamel Case |
396 | | Property | UpperCamelCase |
397 | | Method | UpperCamelCase |
398 | | Class | UpperCamelCase |
399 | | Interface | IUpperCamelCase |
400 | | Local Variable | lowerCamelCase |
401 | | Parameter | lowerCamelCase |
402 |
403 | **Learn More:**
404 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions
405 | https://google.github.io/styleguide/csharp-style.html
406 | https://www.dofactory.com/reference/csharp-coding-standards
407 |
408 | ---
409 |
410 | ## C# Data Types
411 |
412 | ### Value Types
413 |
414 | **For Reference:**
415 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types
416 |
417 | #### Simple Data Types
418 |
419 | **For Reference:**
420 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types
421 |
422 | ##### Bytes
423 |
424 | ```csharp
425 |
426 | byte myUnsignedByte = 8; // Size: 8 bits | Range: 0 to 255
427 | sbyte mySignedByte = -8; // Size: 8 bits | Range: -128 to +127
428 | ```
429 |
430 | ##### Unsigned Integers
431 |
432 | ```csharp
433 |
434 | ushort myUnsignedShort = 16; // Size: 16 bits | Range: 0 to 65535
435 | uint myUnsignedInt = 32; // Size: 32 bits | Range: 0 to 2^32-1
436 | ulong myUnsignedLong = 64; // Size: 64 bits | Range: 0 to 2^64-1
437 | ```
438 |
439 | ##### Signed Integers
440 |
441 | ```csharp
442 | short mySignedShort = 16; // Size: 16 bits | Range: -32768 to +32767
443 | int mySignedInt = 32; // Size: 32 bits | Range: -2^31 to +2^31-1
444 | long mySignedLong = -64; // Size: 64 bits | Range: -2^63 to +2^63-1
445 | ```
446 |
447 | ##### Floating-Point Types
448 |
449 | ```csharp
450 | float myFloat = 3.14F; // Size: 32 bits | Range: 7 digits of precision
451 | double myDouble = 3.14D; // Size: 64 bits | Range: 15-16 digits of precision
452 | decimal myDecimal = 3.14M; // Size: 128 bits | Range: 28-29 digits of precision
453 | ```
454 |
455 | **Learn More:**
456 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types
457 |
458 | ##### Unicode Characters
459 |
460 | ```csharp
461 | char myChar = 'a'; // Size: 16 bits | Range: Unicode character
462 | ```
463 |
464 | ##### Booleans
465 |
466 | ```csharp
467 | bool myBool = true; // Size: 4 bits | Range: true or false
468 | ```
469 |
470 | #### Enum Types
471 |
472 | An enum type is a distinct value type with a set of named constants.
473 |
474 | ```csharp
475 | using System;
476 |
477 | enum Color
478 | {
479 | Red,
480 | Green,
481 | Blue
482 | }
483 |
484 | class Test
485 | {
486 | static void PrintColor(Color color)
487 | {
488 | switch (color)
489 | {
490 | case Color.Red:
491 | Console.WriteLine("Red");
492 | break;
493 | case Color.Green:
494 | Console.WriteLine("Green");
495 | break;
496 | case Color.Blue:
497 | Console.WriteLine("Blue");
498 | break;
499 | default:
500 | Console.WriteLine("Unknown color");
501 | break;
502 | }
503 | }
504 |
505 | static void Main(string[] args)
506 | {
507 | Color c = Color.Red;
508 | PrintColor(c);
509 | PrintColor(Color.Blue);
510 | }
511 | }
512 | ```
513 |
514 | **Learn More:**
515 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum
516 |
517 | #### Structure Types
518 |
519 | Like classes, structs are data structures that can contain data members and function members, but unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly stores the data of the struct, whereas a variable of a class type stores a reference to a dynamically allocated object. Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type object.
520 |
521 | Structs are particularly useful for small data structures that have value semantics. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all good examples of structs. The use of structs rather than classes for small data structures can make a large difference in the number of memory allocations an application performs.
522 |
523 | ```csharp
524 | struct Point
525 | {
526 | public int x, y;
527 |
528 | public Point(int x, int y) {
529 | this.x = x;
530 | this.y = y;
531 | }
532 | }
533 | ```
534 |
535 | **Learn More:**
536 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct
537 |
538 | #### Tuple Types
539 |
540 | Available in C# 7.0 and later, the tuples feature provides concise syntax to group multiple data elements in a lightweight data structure.
541 |
542 | ```csharp
543 | (double, int) t1 = (4.5, 3);
544 | Console.WriteLine($"Tuple with elements {t1.Item1} and {t1.Item2}."); // Output => Tuple with elements 4.5 and 3.
545 |
546 | (double Sum, int Count) t2 = (4.5, 3);
547 | Console.WriteLine($"Sum of {t2.Count} elements is {t2.Sum}."); // Output => Sum of 3 elements is 4.5.
548 | ```
549 |
550 | **Learn More:**
551 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples
552 |
553 | #### Nullable Value Types
554 |
555 | A nullable value type **```T?```** represents all values of its underlying value type **T** and an additional null value. For example, you can assign any of the following three values to a **```bool?```** variable: true, false, or null. An underlying value type **T** cannot be a nullable value type itself.
556 |
557 | ```csharp
558 | int? b = 10;
559 |
560 | if (b.HasValue)
561 | {
562 | Console.WriteLine($"b is {b.Value}");
563 | }
564 |
565 | else
566 | {
567 | Console.WriteLine("b does not have a value");
568 | }
569 | ```
570 |
571 | **Learn More:**
572 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types
573 |
574 | ### Reference Types
575 |
576 | #### Built-In Reference Types
577 |
578 | ##### Object Types
579 |
580 | The object type is an alias for System.Object in .NET. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from System.Object. You can assign values of any type to variables of type object. Any object variable can be assigned to its default value using the literal null.
581 |
582 | ##### String Types
583 |
584 | It is common to think of strings as arrays of characters. In reality, strings in C# are objects.
585 | When you declare a string variable, you basically instantiate an object of type String.
586 |
587 | ```csharp
588 | string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)";
589 | Console.WriteLine(fooString);
590 |
591 | // You can access each character of the string with an indexer:
592 | char charFromString = fooString[1]; // => 'e'
593 |
594 | // Strings are immutable: you can't do fooString[1] = 'X';
595 |
596 | // Compare strings with current culture, ignoring case
597 | string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase);
598 |
599 | // Formatting, based on sprintf
600 | string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2);
601 |
602 | // Dates & Formatting
603 | DateTime fooDate = DateTime.Now;
604 | Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));
605 |
606 | // String Interpolation
607 | string myName = "Jane Doe";
608 | Console.WriteLine($"My name is: {myName}. It is great to be here!");
609 |
610 | // String Builder
611 | StringBuilder sb = new StringBuilder();
612 | sb.Append("Hello ");
613 | sb.AppendLine("World!");
614 | Console.WriteLine(sb);
615 |
616 | // Verbatim String
617 | // You can use the @ symbol before a string literal to escape all characters in the string
618 | string path = "C:\\Users\\User\\Desktop";
619 | string verbatimPath = @"C:\Users\User\Desktop";
620 | Console.WriteLine(path == verbatimPath); // => true
621 |
622 | // You can split a string over two lines with the @ symbol. To escape " use ""
623 | string bazString = @"Here's some stuff
624 | on a new line! ""Wow!"", the masses cried";
625 |
626 | // Popular String Methods & Properties
627 | string myText = "some text";
628 |
629 | Console.WriteLine(myText.IndexOf('t')); // Outputs => 5
630 |
631 | myText = myText.Insert(0, "This is ");
632 | Console.WriteLine(myText); // Outputs => "This is some text"
633 |
634 | myText = myText.Replace("This is", "Here is");
635 | Console.WriteLine(myText); // Outputs => "Here is some text"
636 |
637 | if(myText.Contains("some"))
638 | Console.WriteLine("found"); // Outputs "found"
639 |
640 | myText = myText.Remove(4);
641 | Console.WriteLine(myText); // Outputs "Here"
642 |
643 | myText = myText.Substring(2, 3);
644 | Console.WriteLine(myText); // Outputs "re"
645 | ```
646 |
647 | **Learn More:**
648 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/
649 |
650 | ##### Delegate Types
651 |
652 | A delegate type represents references to methods with a particular parameter list and return type. Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters. Delegates are similar to the concept of function pointers found in some other languages, but unlike function pointers, delegates are object-oriented and type-safe.
653 |
654 | ```csharp
655 | using System;
656 |
657 | delegate double Function(double x);
658 |
659 | class Multiplier
660 | {
661 | double factor;
662 |
663 | public Multiplier(double factor)
664 | {
665 | this.factor = factor;
666 | }
667 |
668 | public double Multiply(double x)
669 | {
670 | return x * factor;
671 | }
672 | }
673 |
674 | class Test
675 | {
676 | static double Square(double x)
677 | {
678 | return x * x;
679 | }
680 |
681 | static double[] Apply(double[] a, Function f)
682 | {
683 | double[] result = new double[a.Length];
684 | for (int i = 0; i < a.Length; i++)
685 | {
686 | result[i] = f(a[i]);
687 | }
688 | return result;
689 | }
690 |
691 | static void Main(string[] args)
692 | {
693 | double[] a = {0.0, 0.5, 1.0};
694 | double[] squares = Apply(a, Square);
695 | double[] sines = Apply(a, Math.Sin);
696 |
697 | Multiplier m = new Multiplier(2.0);
698 | double[] doubles = Apply(a, m.Multiply);
699 | }
700 | }
701 | ```
702 |
703 | **Learn More:**
704 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/
705 |
706 | #### Interface Types
707 |
708 | An interface defines a contract that can be implemented by classes and structs. An interface can contain methods, properties, events, and indexers. An interface does not provide implementations of the members it defines—it merely specifies the members that must be supplied by classes or structs that implement the interface. Interfaces may employ multiple inheritance.
709 |
710 | ```csharp
711 | public interface IShape
712 | {
713 | void Draw();
714 | }
715 | class Circle : IShape
716 | {
717 | public void Draw()
718 | {
719 | Console.WriteLine("Circle Draw");
720 | }
721 | }
722 | static void Main(string[] args)
723 | {
724 | IShape c = new Circle();
725 | c.Draw(); // Outputs "Circle Draw"
726 | }
727 | ```
728 |
729 | **Learn More:**
730 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/
731 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interface
732 |
733 | #### Nullable Reference Types
734 |
735 | Nullable reference types are available beginning with C# 8.0, in code that has opted in to a nullable aware context. Nullable reference types, the null static analysis warnings, and the null-forgiving operator are optional language features. All are turned off by default. A nullable context is controlled at the project level using build settings, or in code using pragmas.
736 |
737 | ```csharp
738 | string notNull = "Hello";
739 | string? nullable = default;
740 | ```
741 |
742 | **Learn More:**
743 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-reference-types
744 |
745 | #### Array Types
746 |
747 | An array is a data structure that contains a number of variables that are accessed through computed indices. The variables contained in an array, also called the elements of the array, are all of the same type, and this type is called the element type of the array.
748 |
749 | Array types are reference types, and the declaration of an array variable simply sets aside space for a reference to an array instance. Actual array instances are created dynamically at run-time using the new operator. The new operation specifies the length of the new array instance, which is then fixed for the lifetime of the instance. The indices of the elements of an array range from 0 to Length - 1. The new operator automatically initializes the elements of an array to their default value, which, for example, is zero for all numeric types and null for all reference types.
750 |
751 | ##### Array Of Simple Types
752 |
753 | ```csharp
754 | int[] a1 = new int[10]; // One-Dimensional Array
755 | int[,] a2 = new int[10, 5]; // Two-Dimensional Array
756 | int[,,] a3 = new int[10, 5, 2]; // Three-Dimensional Array
757 | ```
758 |
759 | ##### Jagged Arrays
760 |
761 | **Jagged Array:** is an array with elements of an array type.
762 |
763 | **Syntax:**
764 |
765 | ```
766 | data_type[][] name_of_array = new data_type[rows][]
767 | ```
768 |
769 | **Example 1:**
770 |
771 | ```csharp
772 | int[][] jaggedArray = new int[3][]; // Jagged Array
773 | jaggedArray[0] = new int[10];
774 | jaggedArray[1] = new int[5];
775 | jaggedArray[2] = new int[20];
776 | ```
777 |
778 | **Example 2:**
779 |
780 | ```csharp
781 | int[][] anotherJaggedArray = new int[][] // Another way to declare Jagged Arrays
782 | {
783 | new int[] {1,8,2,7,9},
784 | new int[] {2,4,6},
785 | new int[] {33,42}
786 | };
787 |
788 | int x = anotherJaggedArray[2][1];
789 | Console.WriteLine(x); // Outputs => 42
790 | ```
791 |
792 | ##### Array Properties & Methods
793 |
794 | The Array class in C# provides various properties and methods to work with arrays.
795 |
796 | The Array class implements the **IEnumerable** interface, so you can **LINQ extension methods** such as Max(), Min(), Sum(), Average() and many others.
797 |
798 | ```csharp
799 | using System;
800 | using System.Linq;
801 |
802 | public class Program
803 | {
804 | public static void Main(string[] args)
805 | {
806 | int[] integersArray = new int[5]{80, 20, 35, 18, 9};
807 |
808 | Console.WriteLine(integersArray.Max());
809 | Console.WriteLine(integersArray.Min());
810 | Console.WriteLine(integersArray.Sum());
811 | Console.WriteLine(integersArray.Average());
812 | }
813 | }
814 | ```
815 |
816 | The **System.Array** class also includes methods for creating, manipulating, searching, and sorting arrays.
817 |
818 | ```csharp
819 | using System;
820 |
821 | public class Program
822 | {
823 | public static void Main(string[] args)
824 | {
825 | int[] integersArray = {20, 9, 16, 50, 3};
826 |
827 | Console.WriteLine("Original Array:");
828 | foreach(int element in integersArray)
829 | {
830 | Console.WriteLine(element);
831 | }
832 |
833 | Console.WriteLine("Sorted Array:");
834 | Array.Sort(integersArray);
835 | foreach(int element in integersArray)
836 | {
837 | Console.WriteLine(element);
838 | }
839 |
840 | Console.WriteLine("Reversed Array:");
841 | Array.Reverse(integersArray);
842 | Array.ForEach(integersArray, n => Console.WriteLine(n));
843 |
844 | Console.WriteLine(Array.BinarySearch(integersArray, 9));
845 | }
846 | }
847 | ```
848 |
849 | **Learn More:**
850 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/
851 | https://docs.microsoft.com/en-us/dotnet/api/system.array
852 | https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable
853 |
854 | ---
855 |
856 | ## Type Casting
857 |
858 | Type casting is when you assign a value of one data type to another type.
859 |
860 | In C#, there are two types of casting:
861 |
862 | **Implicit Casting (automatically)** - converting a smaller type to a larger type size
863 |
864 | > char -> int -> long -> float -> double
865 |
866 | **Explicit Casting (manually)** - converting a larger type to a smaller size type:
867 |
868 | > double -> float -> long -> int -> char
869 |
870 | ### Implicit Casting
871 |
872 | Implicit casting is done automatically when passing a smaller size type to a larger size type.
873 |
874 | ```csharp
875 | int myInt = 9;
876 | double myDouble = myInt; // Automatic casting: int to double
877 |
878 | Console.WriteLine(myInt); // Outputs 9
879 | Console.WriteLine(myDouble); // Outputs 9
880 | ```
881 |
882 | ### Explicit Casting
883 |
884 | Explicit casting must be done manually by placing the type in parentheses in front of the value.
885 |
886 | ```csharp
887 | double myDouble = 9.78;
888 | int myInt = (int) myDouble; // Manual casting: double to int
889 |
890 | Console.WriteLine(myDouble); // Outputs 9.78
891 | Console.WriteLine(myInt); // Outputs 9
892 | ```
893 |
894 | ### Type Conversion Methods
895 |
896 | It is also possible to convert data types explicitly by using built-in methods.
897 |
898 | - ToBoolean
899 | - ToByte
900 | - ToChar
901 | - ToDateTime
902 | - ToDecimal
903 | - ToDouble
904 | - ToInt16
905 | - ToInt32
906 | - ToInt64
907 | - ToSbyte
908 | - ToSingle
909 | - ToString
910 | - ToType
911 | - ToUInt16
912 | - ToUInt32
913 | - ToUInt64
914 |
915 | ```csharp
916 | int myInt = 10;
917 | double myDouble = 5.25;
918 | bool myBool = true;
919 |
920 | Console.WriteLine(Convert.ToString(myInt)); // convert int to string
921 | Console.WriteLine(Convert.ToDouble(myInt)); // convert int to double
922 | Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int
923 | Console.WriteLine(Convert.ToString(myBool)); // convert bool to string
924 | ```
925 |
926 | **Learn More:**
927 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions
928 |
929 | ---
930 |
931 | ## Operators
932 |
933 | ### Arithmetic Operators
934 |
935 | ```csharp
936 | float myFloat = 0;
937 |
938 | myFloat = 3 + 2; // Addition => 5
939 | myFloat = 3 - 2; // Subtraction => 1
940 | myFloat = 3 * 2; // Multiplication => 6
941 | myFloat = 3 / 2; // Division => 1
942 | myFloat = 3 % 2; // Modulus => 1
943 |
944 | /*
945 | Notice that the division sign gives an incorrect result.
946 | This is because it operates on two integer values and will therefore round the result and return an integer.
947 | To get the correct value, one of the numbers needs to be converted into a floating-point number.
948 | */
949 | myFloat = 3 / (float) 2; // 1.5
950 | ```
951 |
952 | ### Combined Assignment Operators
953 |
954 | ```csharp
955 | float myFloat = 0;
956 |
957 | myFloat += 2; // myNumber = myNumber + 2
958 | myFloat -= 2; // myNumber = myNumber - 2
959 | myFloat *= 2; // myNumber = myNumber * 2
960 | myFloat /= 2; // myNumber = myNumber / 2
961 | myFloat %= 2; // myNumber = myNumber % 2
962 | ```
963 |
964 | ### Increment and Decrement Operators
965 |
966 | ```csharp
967 | int myCounter = 0;
968 |
969 | Console.WriteLine(myCounter++); //Prints "0", _myCounter = 1. Post-Incrementation
970 | Console.WriteLine(++myCounter); //Prints "2", _myCounter = 2. Pre-Incrementation
971 | Console.WriteLine(myCounter--); //Prints "2", _myCounter = 1. Post-Decrementation
972 | Console.WriteLine(--myCounter); //Prints "0", _myCounter = 0. Pre-Decrementation
973 | ```
974 |
975 | ### Comparison Operators
976 |
977 | ```csharp
978 | Console.WriteLine($"3 == 2? {3 == 2}"); // => false
979 | Console.WriteLine($"3 != 2? {3 != 2}"); // => true
980 | Console.WriteLine($"3 > 2? {3 > 2}"); // => true
981 | Console.WriteLine($"3 < 2? {3 < 2}"); // => false
982 | Console.WriteLine($"2 <= 2? {2 <= 2}"); // => true
983 | Console.WriteLine($"2 >= 2? {2 >= 2}"); // => true
984 | ```
985 |
986 | ### Logical Operators
987 |
988 | ```csharp
989 | bool myBool;
990 |
991 | myBool = (true && false); // Logical AND => (false)
992 | myBool = (true || false); // Logical OR => (true)
993 | myBool = !(true); // Logical NOT => (false)
994 |
995 | Console.WriteLine(myBool);
996 | ```
997 |
998 | ### Bitwise Operators
999 |
1000 | ```csharp
1001 | int myInteger;
1002 |
1003 | // The bitwise operators can manipulate individual bits inside an integer.
1004 |
1005 | myInteger = 5 & 4; // and (0b101 & 0b100 = 0b100 = 4)
1006 | myInteger = 5 | 4; // or (0b101 | 0b100 = 0b101 = 5)
1007 | myInteger = 5 ^ 4; // xor (0b101 ^ 0b100 = 0b001 = 1)
1008 | myInteger = 4 << 1; // left shift (0b100 << 1 = 0b1000 = 8)
1009 | myInteger = 4 >> 1; // right shift (0b100 >> 1 = 0b10 = 2)
1010 | myInteger = ~ 4; // invert (~0b00000100 = 0b11111011 = -5)
1011 |
1012 | // These bitwise operators have shorthand assignment operators, just like the arithmetic operators.
1013 |
1014 | myInteger = 5;
1015 | myInteger &= 4; // and (0b101 & 0b100 = 0b100 = 4)
1016 |
1017 | myInteger = 5;
1018 | myInteger |= 4; // or (0b101 | 0b100 = 0b101 = 5)
1019 |
1020 | myInteger = 5;
1021 | myInteger ^= 4; // xor (0b101 ^ 0b100 = 0b001 = 1)
1022 |
1023 | myInteger = 5;
1024 | myInteger <<= 1; // left shift (0b101 << 1 = 0b1010 = 10)
1025 |
1026 | myInteger = 5;
1027 | myInteger >>= 1; // right shift (0b101 >> 1 = 0b10 = 2)
1028 | ```
1029 |
1030 | ### Operator Precedents
1031 |
1032 | ```csharp
1033 | /*
1034 |
1035 | - parentheses ()
1036 |
1037 | - Postfix Increment and Decrement ++, --
1038 | - Prefix Increment, Decrement and Unary ++, --, +, -, !, ~
1039 |
1040 | - Multiplicative *, /, %
1041 | - Additive +, -
1042 |
1043 | - Shift <<, >>
1044 | - Relational <, <=, >, >=
1045 | - Equality ==, !=
1046 |
1047 | - Bitwise AND &
1048 | - Bitwise XOR ^
1049 | - Bitwise OR |
1050 |
1051 | - Logical AND &&
1052 | - Logical OR ||
1053 |
1054 | - Ternary ? :
1055 | - Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
1056 |
1057 | */
1058 | ```
1059 |
1060 | The higher the precedence of operator is, the higher it appears in the table.
1061 |
1062 | To make things clearer, parentheses () can be used to specify which part of the expression will be evaluated first. Parentheses have the greatest precedence of all operators.
1063 |
1064 | ```csharp
1065 | int myInteger;
1066 |
1067 | myInteger = 4 + 6 / 2; // => 7
1068 | myInteger = (4 + 6) / 2; // => 5
1069 | ```
1070 |
1071 | **Learn More:**
1072 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/
1073 |
1074 | ---
1075 |
1076 | ## Statements
1077 |
1078 | ### Conditions
1079 |
1080 | #### **```if```**...**```else if```**...**```else```**
1081 | ```csharp
1082 | int time = 22;
1083 |
1084 | if (time < 10)
1085 | {
1086 | Console.WriteLine("Good morning.");
1087 | }
1088 | else if (time < 20)
1089 | {
1090 | Console.WriteLine("Good day.");
1091 | }
1092 | else
1093 | {
1094 | Console.WriteLine("Good evening.");
1095 | }
1096 |
1097 | // Ternary operators
1098 | // A simple if/else can be written as follows
1099 | // ? :
1100 | int toCompare = 17;
1101 | string isTrue = toCompare == 17 ? "True" : "False";
1102 | ```
1103 |
1104 | #### **```switch```** Case
1105 |
1106 | ```csharp
1107 | // A switch works with the byte, short, char, and int data types.
1108 | // It also works with enumerated types (discussed in Enum Types),
1109 | // the String class, and a few special classes that wrap
1110 | // primitive types: Character, Byte, Short, and Integer.
1111 | int month = 3;
1112 | string monthString;
1113 | switch (month)
1114 | {
1115 | case 1:
1116 | monthString = "January";
1117 | break;
1118 | case 2:
1119 | monthString = "February";
1120 | break;
1121 | case 3:
1122 | monthString = "March";
1123 | break;
1124 | // You can assign more than one case to an action
1125 | // But you can't add an action without a break before another case
1126 | // (if you want to do this, you would have to explicitly add a goto case x
1127 | case 6:
1128 | case 7:
1129 | case 8:
1130 | monthString = "Summer time!!";
1131 | break;
1132 | default:
1133 | monthString = "Some other month";
1134 | break;
1135 | }
1136 | ```
1137 |
1138 | ### Loops
1139 |
1140 | #### **```while```** Loop
1141 |
1142 | ```csharp
1143 |
1144 | int fooWhile = 0;
1145 |
1146 | while (fooWhile < 100)
1147 | {
1148 | // Iterated 100 times, fooWhile 0->99
1149 | fooWhile++;
1150 | }
1151 | ```
1152 |
1153 | #### **```do```**...**```while```** Loop
1154 |
1155 | ```csharp
1156 | // Do While Loop
1157 | int fooDoWhile = 0;
1158 |
1159 | do
1160 | {
1161 | // Start iteration 100 times, fooDoWhile 0->99
1162 | if (false)
1163 | {
1164 | continue; // skip the current iteration
1165 | }
1166 |
1167 | fooDoWhile++;
1168 |
1169 | if (fooDoWhile == 50)
1170 | {
1171 | break; // breaks from the loop completely
1172 | }
1173 |
1174 | } while (fooDoWhile < 100);
1175 | ```
1176 |
1177 | #### **```for```** Loop
1178 |
1179 | ```csharp
1180 | for (int fooFor = 0; fooFor < 10; fooFor++)
1181 | {
1182 | // Iterated 10 times, fooFor 0->9
1183 | }
1184 | ```
1185 |
1186 | #### **```foreach```** Loop
1187 |
1188 | ```csharp
1189 | foreach (char character in "Hello World".ToCharArray())
1190 | {
1191 | // Iterated over all the characters in the string
1192 | }
1193 | ```
1194 |
1195 | ### **```goto```** Statement
1196 |
1197 | ```csharp
1198 | static void Main(string[] args) {
1199 | int i = 0;
1200 | goto check;
1201 |
1202 | loop:
1203 | Console.WriteLine(args[i++]);
1204 |
1205 | check:
1206 | if (i < args.Length)
1207 | {
1208 | goto loop;
1209 | }
1210 | }
1211 | ```
1212 |
1213 | ### **```return```** Statement
1214 |
1215 | ```csharp
1216 | static int Add(int a, int b)
1217 | {
1218 | return a + b;
1219 | }
1220 |
1221 | static void Main(string[] args)
1222 | {
1223 | Console.WriteLine(Add(1, 2));
1224 | return;
1225 | }
1226 | ```
1227 |
1228 | ### **```yield```** Statement
1229 |
1230 | ```csharp
1231 | static IEnumerable Range(int from, int to)
1232 | {
1233 | for (int i = from; i < to; i++)
1234 | {
1235 | yield return i;
1236 | }
1237 | yield break;
1238 | }
1239 |
1240 | static void Main(string[] args)
1241 | {
1242 | foreach (int x in Range(-10,10))
1243 | {
1244 | Console.WriteLine(x);
1245 | }
1246 | }
1247 | ```
1248 |
1249 | ### **```checked```** and **```unchecked```** Statements
1250 |
1251 | ```csharp
1252 | static void Main(string[] args)
1253 | {
1254 | int i = int.MaxValue;
1255 | checked
1256 | {
1257 | Console.WriteLine(i + 1); // Exception
1258 | }
1259 | unchecked
1260 | {
1261 | Console.WriteLine(i + 1); // Overflow
1262 | }
1263 | }
1264 | ```
1265 |
1266 | ### **```lock```** Statement
1267 |
1268 | ```csharp
1269 | class Account
1270 | {
1271 | decimal balance;
1272 | public void Withdraw(decimal amount)
1273 | {
1274 | lock (this)
1275 | {
1276 | if (amount > balance)
1277 | {
1278 | throw new Exception("Insufficient funds");
1279 | }
1280 | balance -= amount;
1281 | }
1282 | }
1283 | }
1284 | ```
1285 |
1286 | ### **```using```** Statement
1287 |
1288 | ```csharp
1289 | static void Main(string[] args)
1290 | {
1291 | using (TextWriter w = File.CreateText("test.txt"))
1292 | {
1293 | w.WriteLine("Line one");
1294 | w.WriteLine("Line two");
1295 | w.WriteLine("Line three");
1296 | }
1297 | }
1298 | ```
1299 |
1300 | ### Exception Handling
1301 |
1302 | ```csharp
1303 | static double Divide(double x, double y)
1304 | {
1305 | if (y == 0)
1306 | {
1307 | throw new DivideByZeroException();
1308 | }
1309 | return x / y;
1310 | }
1311 |
1312 | static void Main(string[] args)
1313 | {
1314 | try
1315 | {
1316 | if (args.Length != 2)
1317 | {
1318 | throw new Exception("Two numbers are required");
1319 | }
1320 | double x = double.Parse(args[0]);
1321 | double y = double.Parse(args[1]);
1322 | Console.WriteLine(Divide(x, y));
1323 | }
1324 |
1325 | catch (Exception e)
1326 | {
1327 | Console.WriteLine(e.Message);
1328 | }
1329 |
1330 | finally
1331 | {
1332 | Console.WriteLine("Terminating!");
1333 | }
1334 | }
1335 | ```
1336 |
1337 | **Learn More:**
1338 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/statements
1339 |
1340 | ---
1341 |
1342 | ## Classes & Objects
1343 |
1344 | Classes are the most fundamental of C#'s types. A class is a data structure that combines state (fields) and actions (methods and other function members) in a single unit. A class provides a definition for dynamically created instances of the class, also known as objects. Classes support inheritance and polymorphism, mechanisms whereby derived classes can extend and specialize base classes.
1345 |
1346 | New classes are created using class declarations. A class declaration starts with a header that specifies the attributes and modifiers of the class, the name of the class, the base class (if given), and the interfaces implemented by the class. The header is followed by the class body, which consists of a list of member declarations written between the delimiters { and }.
1347 |
1348 | You can find an example below that demonstrates a class with a constructor and destructor.
1349 |
1350 | ```csharp
1351 | using System;
1352 |
1353 | namespace Example
1354 | {
1355 | class Complex
1356 | {
1357 | private int realNum, imaginaryNum;
1358 |
1359 | // Defining the constructor
1360 | public Complex()
1361 | {
1362 | realNum = 0;
1363 | imaginaryNum = 0;
1364 | }
1365 |
1366 | // SetValue method sets value of real and img
1367 | public void SetValue(int r, int i)
1368 | {
1369 | realNum = r;
1370 | imaginaryNum = i;
1371 | }
1372 |
1373 | // DisplayValue displays values of real and img
1374 | public void DisplayValue()
1375 | {
1376 | Console.WriteLine("Real = " + realNum);
1377 | Console.WriteLine("Imaginary = " + imaginaryNum);
1378 | }
1379 |
1380 | // Defining the destructor for class Complex
1381 | ~Complex()
1382 | {
1383 | Console.WriteLine("Destructor was called");
1384 | }
1385 |
1386 | }
1387 |
1388 | class Program
1389 | {
1390 | static void Main(string[] args)
1391 | {
1392 | // Creating an instance of class Complex C invokes constructor
1393 | Complex myComplexNumber = new Complex();
1394 |
1395 | // Calling SetValue method using instance C Setting values of real to 2 and img to 3
1396 | myComplexNumber.SetValue(2, 3);
1397 |
1398 | // Displaying values of real and imaginary parts
1399 | myComplexNumber.DisplayValue();
1400 | }
1401 | }
1402 | }
1403 | ```
1404 |
1405 | **Learn More:**
1406 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/classes
1407 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/objects
1408 |
1409 | ### Members
1410 |
1411 | The members of a class are either static members or instance members. Static members belong to classes, and instance members belong to objects (instances of classes).
1412 |
1413 | The following table provides an overview of the kinds of members a class can contain.
1414 |
1415 | | Member | Description |
1416 | | ------------ | ------------------------------------------------------------ |
1417 | | Constants | Constant values associated with the class |
1418 | | Fields | Variables of the class |
1419 | | Methods | Computations and actions that can be performed by the class |
1420 | | Properties | Actions associated with reading and writing named properties of the class |
1421 | | Indexers | Actions associated with indexing instances of the class like an array |
1422 | | Events | Notifications that can be generated by the class |
1423 | | Operators | Conversions and expression operators supported by the class |
1424 | | Constructors | Actions required to initialize instances of the class or the class itself |
1425 | | Destructors | Actions to perform before instances of the class are permanently discarded |
1426 | | Types | Nested types declared by the class |
1427 |
1428 | ### Constructors
1429 |
1430 | Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.
1431 |
1432 | **Note:** You can also chain and overload constructors when needed.
1433 |
1434 | ```csharp
1435 | class MyRectangle
1436 | {
1437 | public int x, y;
1438 |
1439 | public MyRectangle(int width, int height) // Defining the constructor
1440 | {
1441 | x = width;
1442 | y = height;
1443 | }
1444 |
1445 | static void Main(string[] args)
1446 | {
1447 | MyRectangle r = new MyRectangle(20, 15);
1448 | }
1449 | }
1450 | ```
1451 |
1452 | **Learn More:**
1453 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors
1454 |
1455 | ### The ```this``` Keyword
1456 |
1457 | Inside the constructor, as well as in other methods belonging to the object, a special keyword called this can be used. This keyword is a reference to the current instance of the class. Suppose, for example, that the constructor’s parameters have the same names as the corresponding fields. The fields could then still be accessed by using the this keyword, even though they are overshadowed by the parameters.
1458 |
1459 | ```csharp
1460 | class MyRectangle
1461 | {
1462 | public int x, y;
1463 |
1464 | public MyRectangle(int x, int y)
1465 | {
1466 | this.x = x; // Set field x to parameter x
1467 | this.y = y; // Set field y to parameter y
1468 | }
1469 | }
1470 | ```
1471 |
1472 | **Learn More:**
1473 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/this
1474 |
1475 | ### Garbage Collector
1476 |
1477 | The .NET Framework has a garbage collector that periodically releases memory used by objects when they are no longer accessible. This frees the programmer from the often tedious and error-prone task of manual memory management.
1478 |
1479 | An object will be eligible for destruction when there are no more references to it.
1480 |
1481 | **Note:** Objects cannot be explicitly deallocated in C#.
1482 |
1483 | ```csharp
1484 | static void Main(string[] args)
1485 | {
1486 | if (true)
1487 | {
1488 | int myNum = 0;
1489 | }
1490 | // Integer myNum becomes inaccessible here and will be destroyed.
1491 | }
1492 | ```
1493 |
1494 | **Learn More:**
1495 | https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals
1496 |
1497 | ### Destructors / Finalizers
1498 |
1499 | The destructor or finilizer is used to release any unmanaged resources allocated by the object. It is called automatically before an object is destroyed and cannot be called explicitly.
1500 |
1501 | - A class can only have one destructor.
1502 | - Destructors cannot be called. They are invoked automatically.
1503 | - A destructor does not take modifiers or have parameters.
1504 | - The name of a destructor is exactly the same as the class prefixed with a tilde (```~```).
1505 |
1506 | ```csharp
1507 | class Message
1508 | {
1509 | public Message() // Defining the construtor
1510 | {
1511 | Console.WriteLine("The constructor is called");
1512 | }
1513 |
1514 | ~Message() // Defining the desctructor
1515 | {
1516 | Console.WriteLine("The destructor is called");
1517 | }
1518 | }
1519 |
1520 | static void Main(string[] args)
1521 | {
1522 | Message myMessage = new Message();
1523 | }
1524 | ```
1525 |
1526 | **Note:** The .NET Framework garbage collector automatically manages the allocation and release of memory for objects. However, when a class uses unmanaged resources - such as network connections, files, and user interface components – a destructor should be used to free up those resources when they are no longer needed.
1527 |
1528 | **Learn More:**
1529 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/destructors
1530 |
1531 | ---
1532 |
1533 | ## Object-Oriented Programming (OOP)
1534 |
1535 | C# is an object-oriented language. Four of the key techniques used in object-oriented programming are:
1536 |
1537 | - **Abstraction** means hiding the unnecessary details from type consumers.
1538 | - **Encapsulation** means that a group of related properties, methods, and other members are treated as a single unit or object.
1539 | - **Inheritance** describes the ability to create new classes based on an existing class.
1540 | - **Polymorphism** means that you can have multiple classes that can be used interchangeably, even though each class implements the same properties or methods in different ways.
1541 |
1542 | **Learn More:**
1543 | https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/intro-to-csharp/object-oriented-programming
1544 |
1545 | ### Encapsulation / Access Levels
1546 |
1547 | In programming, encapsulation means more than simply combining members together within a class; it also means restricting access to the inner workings of that class.
1548 | Encapsulation is implemented by using access modifiers. An access modifier defines the scope and visibility of a class member.
1549 |
1550 | Each member of a class has an associated accessibility, which controls the regions of program text that are able to access the member. There are five possible forms of accessibility. These are summarized in the following tables.
1551 |
1552 | | Access Modifier | Meaning |
1553 | | ------------------ | ------------------------------------------------------------ |
1554 | | public | Access not limited |
1555 | | protected | Access limited to this class or classes derived from this class |
1556 | | internal | Access limited to this program |
1557 | | protected internal | Access limited to this program or classes derived from this class |
1558 | | private | Access limited to this class |
1559 |
1560 | **Note:** When choosing an access level, it is generally best to use the most restrictive level possible.
1561 |
1562 | | Accessibility | Meaning |
1563 | | ------------- | ------------------------------------------------------------ |
1564 | | Events | Notifications that can be generated by the class |
1565 | | Operators | Conversions and expression operators supported by the class |
1566 | | Constructors | Actions required to initialize instances of the class or the class itself |
1567 | | Destructors | Actions to perform before instances of the class are permanently discarded |
1568 | | Types | Nested types declared by the class |
1569 |
1570 | ### Inheritance
1571 |
1572 | Inheritance allows a class to acquire the members of another class. It allows to define a class based on another class. This makes creating and maintaining an application easy.
1573 |
1574 | The class whose properties are inherited by another class is called the **Base class**.
1575 | The class which inherits the properties is called the **Derived class**.
1576 |
1577 | **Note:** C# does not support multiple inheritance. However, you can use interfaces to implement multiple inheritance.
1578 |
1579 | ```csharp
1580 | using System;
1581 |
1582 | namespace RectangleApplication
1583 | {
1584 | class Rectangle
1585 | {
1586 | protected double length;
1587 | protected double width;
1588 |
1589 | public Rectangle(double l, double w)
1590 | {
1591 | length = l;
1592 | width = w;
1593 | }
1594 |
1595 | public double GetArea()
1596 | {
1597 | return length * width;
1598 | }
1599 |
1600 | public void Display()
1601 | {
1602 | Console.WriteLine($"Length: {length}");
1603 | Console.WriteLine($"Width: {width}");
1604 | Console.WriteLine($"Area: {GetArea()}");
1605 | }
1606 | }
1607 |
1608 | class Tabletop : Rectangle
1609 | {
1610 | private double cost;
1611 | public Tabletop(double l, double w) : base(l, w) { }
1612 |
1613 | public double GetCost()
1614 | {
1615 | double cost;
1616 | cost = GetArea() * 70;
1617 |
1618 | return cost;
1619 | }
1620 |
1621 | public void Display()
1622 | {
1623 | base.Display();
1624 | Console.WriteLine($"Cost: {GetCost()}");
1625 | }
1626 | }
1627 |
1628 | class ExecuteRectangle
1629 | {
1630 | static void Main(string[] args)
1631 | {
1632 | Tabletop myTabletop = new Tabletop(4.5, 8.5);
1633 | myTabletop.Display();
1634 | }
1635 | }
1636 | }
1637 | ```
1638 |
1639 | **Learn More:**
1640 | https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/inheritance
1641 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/inheritance
1642 |
1643 | ### Polymorphism / Redefining Members
1644 |
1645 | The word polymorphism means "having many forms". In C#, polymorphism means that a single method can have a number of different implementations. Typically, polymorphism occurs when there is a hierarchy of classes and they are related through inheritance from a common base class.
1646 |
1647 | Polymorphism means that a call to a member method will cause a different implementation to be executed depending on the type of object that invokes the method.
1648 |
1649 | ```csharp
1650 | using System;
1651 |
1652 | namespace SamplePolymorphism
1653 | {
1654 | class Program
1655 | {
1656 | class Shape
1657 | {
1658 | // The "virtual" keyword is used below to allow the method to be overridden in a derived class.
1659 | public virtual void Draw()
1660 | {
1661 | Console.WriteLine("The act of drawing!");
1662 | }
1663 | }
1664 |
1665 | class Circle : Shape
1666 | {
1667 | // The "override" modifier is required for modifying the virtual implementation of the inherited method.
1668 | public override void Draw()
1669 | {
1670 | Console.WriteLine("Draw a circle");
1671 | }
1672 | }
1673 |
1674 | class Rectangle : Shape
1675 | {
1676 | public override void Draw()
1677 | {
1678 | Console.WriteLine("Draw a rectangle");
1679 | }
1680 | }
1681 |
1682 | static void Main(string[] args)
1683 | {
1684 | Shape myCircle = new Circle();
1685 | myCircle.Draw();
1686 |
1687 | Shape myRectangle = new Rectangle();
1688 | myRectangle.Draw();
1689 | }
1690 | }
1691 | }
1692 | ```
1693 |
1694 | **Learn More:**
1695 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/polymorphism
1696 |
1697 | ### Static
1698 |
1699 | Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object.
1700 |
1701 | The static modifier can be used to declare static classes. In classes, interfaces, and structs, you may add the static modifier to fields, methods, properties, operators, events, and constructors.
1702 |
1703 | **Note 1:** The static modifier can't be used with indexers or finalizers.
1704 | **Note 2:** An entire class can be declared as static.
1705 | **Note 3:** A static class can contain only static members.
1706 | **Note 4:** You cannot instantiate an object of a static class, as only one instance of the static class can exist in a program.
1707 |
1708 | Beginning with C# 8.0, you can add the static modifier to a local function. A static local function can't capture local variables or instance state.
1709 |
1710 | Beginning with C# 9.0, you can add the static modifier to a lambda expression or anonymous method. A static lambda or anonymous method can't capture local variables or instance state.
1711 |
1712 | ```csharp
1713 | using System;
1714 |
1715 | namespace StaticDemonstration
1716 | {
1717 | static class User
1718 | {
1719 | // Static Variables
1720 | public static string name;
1721 | public static string location;
1722 | public static int age;
1723 |
1724 | // Static Method
1725 | public static void Details()
1726 | {
1727 | Console.WriteLine($"The user details are: {name} - {age} - {location}");
1728 | }
1729 | }
1730 |
1731 | class Program
1732 | {
1733 | static void Main(string[] args)
1734 | {
1735 | // Assigning values to public static variables:
1736 | User.name = "Kayako Yamada";
1737 | User.location = "Japan";
1738 | User.age = 30;
1739 |
1740 | // Accessing public static variables:
1741 | Console.WriteLine($"Name: {User.name}");
1742 | Console.WriteLine($"Location: {User.location}");
1743 | Console.WriteLine($"Age: {User.age}");
1744 |
1745 | // Calling a public static method:
1746 | User.Details();
1747 | }
1748 | }
1749 | }
1750 | ```
1751 |
1752 | **Learn More:**
1753 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static
1754 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members
1755 |
1756 | ### Properties
1757 |
1758 | Properties in C# provide the ability to protect a field by reading and writing to it through special methods called **accessors**. They are generally declared as ```public``` with the same data type as the field they are going to protect, followed by the name of the property and a code block that defines the ```get``` and ```set``` accessors.
1759 |
1760 | Properties allow developers to change the internal implementation of the property without breaking any programs that are using it.
1761 |
1762 | **Note 1:** It is a good practice to encapsulate members of a class and provide access to them only through public methods. Properties provide a flexible mechanism to read, write, or compute the value of a private field.
1763 | **Note 2:** It is advised for the property name to be the same as the private field with a capital letter.
1764 | **Note 3:** Any accessor of a property can be omitted depending on the objective and design of the program.
1765 | **Note 4:** A property can also be private, so it can be called only from within the class.
1766 |
1767 | ```csharp
1768 | using System;
1769 |
1770 | namespace PropertiesDemonstration
1771 | {
1772 | class Person
1773 | {
1774 | private string name; // Private string that requires a property to access it from outside the class.
1775 | private ushort age; // Private unsigned short that requires a property to access it from outside the class.
1776 |
1777 | public string Name // Property of type string.
1778 | {
1779 | get { return name; }
1780 | set { name = value; }
1781 | // "value" is a keyword, which represents the value we assign to a property using the set accessor.
1782 | }
1783 |
1784 | public ushort Age // Property of type string.
1785 | {
1786 | get { return age; }
1787 |
1788 | set
1789 | {
1790 | if (value >= 18) // Validating the value before assigning it to the private member.
1791 | {
1792 | age = value;
1793 | }
1794 | }
1795 | }
1796 |
1797 | public string Title { get; set; }
1798 | // Title is an auto-implemented property (Auto-Properties). It allows you to define the property without declaring the private field name separately. It is created by the property automatically. That allows a short declaration of private members.
1799 |
1800 | static void Main(string[] args)
1801 | {
1802 | Person teacher = new Person();
1803 |
1804 | teacher.Name = "James";
1805 | teacher.Title = "Dr.";
1806 | teacher.Age = 38;
1807 |
1808 | Console.WriteLine($"Welcome: {teacher.Title} {teacher.Name} {teacher.age}");
1809 | }
1810 | }
1811 | }
1812 | ```
1813 |
1814 | **Learn More:**
1815 | https://docs.microsoft.com/en-us/dotnet/csharp/properties
1816 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
1817 |
1818 | ### Indexers
1819 |
1820 | Indexers allow instances of a class or struct to be indexed just like arrays. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters.
1821 |
1822 | Declaration of an **indexer** is to some extent similar to a **property**. The difference is that **indexer** accessors require an **index**. Like a property, you use get and set accessors for defining an indexer. However, where properties return or set a specific data member, indexers return or set a particular value from the object instance.
1823 |
1824 | **Note 1:** Indexers are defined with the ```this``` keyword.
1825 | **Note 2:** Usually, programmers use indexers when a class represents a list, collection, or an array of objects.
1826 |
1827 | ```csharp
1828 | using System;
1829 |
1830 | namespace IndexerDemonstration
1831 | {
1832 | class Program
1833 | {
1834 | class Clients
1835 | {
1836 | private string[] names = new string[10];
1837 |
1838 | public string this[int index]
1839 | {
1840 | get
1841 | {
1842 | return names[index];
1843 | }
1844 |
1845 | set
1846 | {
1847 | names[index] = value;
1848 | }
1849 | }
1850 | }
1851 |
1852 | static void Main(string[] args)
1853 | {
1854 | Clients myClients = new Clients();
1855 |
1856 | myClients[0] = "Jane";
1857 | myClients[1] = "Oliver";
1858 | myClients[2] = "Amy";
1859 |
1860 | Console.WriteLine(myClients[1]); // Oliver
1861 | }
1862 | }
1863 | }
1864 | ```
1865 |
1866 | **Learn More:**
1867 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/
1868 |
1869 | ### Abstraction
1870 |
1871 | #### Abstract Classes & Methods
1872 |
1873 | Polymorphism is used when you have different derived classes with the same method, which has different implementations in each class. This behavior is achieved through ```virtual``` methods that are **overridden** in the derived classes.
1874 |
1875 | In some situations there is no meaningful need for the ```virtual``` method to have a separate definition in the base class. These methods are defined using the ```abstract``` keyword and specify that the derived classes must define that method on their own.
1876 |
1877 | The **abstract modifier** indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events.
1878 |
1879 | Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes, not instantiated on its own. Members marked as abstract must be implemented by non-abstract classes that derive from the abstract class.
1880 |
1881 | **Note:** You cannot create objects of a class containing an abstract method, which is why the class itself should be abstract.
1882 |
1883 | ```csharp
1884 | using System;
1885 |
1886 | abstract class BaseClass // Abstract Class
1887 | {
1888 | // Protected Integers
1889 | protected int _x = 0;
1890 | protected int _y = 0;
1891 |
1892 | // Public Abstract Method
1893 | public abstract void IncrementValues();
1894 |
1895 | // Abstract Properties
1896 | public abstract int X { get; }
1897 | public abstract int Y { get; }
1898 | }
1899 |
1900 | class DerivedClass : BaseClass
1901 | {
1902 | public override void IncrementValues()
1903 | {
1904 | _x++;
1905 | _y++;
1906 | }
1907 |
1908 | public override int X // Overriding Property
1909 | {
1910 | get
1911 | {
1912 | return _x;
1913 | }
1914 | }
1915 |
1916 | public override int Y // Overriding Property
1917 | {
1918 | get
1919 | {
1920 | return _y;
1921 | }
1922 | }
1923 |
1924 | static void Main(string[] args)
1925 | {
1926 | var myObject = new DerivedClass();
1927 | myObject.IncrementValues(); // Incrementing X & Y by one
1928 | Console.WriteLine($"x = {myObject.X}, y = {myObject.Y}"); // x = 1, y = 1
1929 | }
1930 | }
1931 | ```
1932 |
1933 | **Learn More:**
1934 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/abstract
1935 |
1936 | #### Interfaces
1937 |
1938 | An interface is a completely abstract class, which contains only abstract members. It is declared using the ```interface``` keyword.
1939 |
1940 | When a class implements an interface, it must also implement, or define, all of its methods.
1941 |
1942 | The term "**implementing an interface**"" is used (opposed to the term "inheriting from") to describe the process of creating a class based on an interface. The interface simply describes what a class should do. The class implementing the interface must define how to accomplish the behaviors.
1943 |
1944 | A class can inherit from just one base class, but it can implement **multiple interfaces**. Therefore, by using interfaces you can include behavior from multiple sources in a class. To implement multiple interfaces, use a comma separated list of interfaces when creating the class.
1945 |
1946 | **Note 1:** All members of the interface are by default abstract, so no need to use the abstract keyword.
1947 | **Note 2:** All members of an interface are always public, and no access modifiers can be applied to them.
1948 | **Note 3:** It is common to use the capital letter **I** as the starting letter for an interface name.
1949 | **Note 4:** Interfaces cannot contain fields (variables).
1950 |
1951 | ```csharp
1952 | using System;
1953 |
1954 | namespace InterfacesDemonstration
1955 | {
1956 | interface IInfo
1957 | {
1958 | void DoInform();
1959 | }
1960 |
1961 | interface IVersion
1962 | {
1963 | void GetVersion();
1964 | }
1965 |
1966 | interface ILog : IInfo, IVersion
1967 | {
1968 | void DoLog();
1969 | }
1970 |
1971 | class DBConnect : ILog
1972 | {
1973 | public void DoInform()
1974 | {
1975 | Console.WriteLine("This is the DBConnect class");
1976 | }
1977 |
1978 | public void GetVersion()
1979 | {
1980 | Console.WriteLine("Version 1.0.0");
1981 | }
1982 |
1983 | public void DoLog()
1984 | {
1985 | Console.WriteLine("Logging");
1986 | }
1987 |
1988 | public void Connect()
1989 | {
1990 | Console.WriteLine("Connecting to the database");
1991 | }
1992 | }
1993 |
1994 | class Program
1995 | {
1996 | static void Main(string[] args)
1997 | {
1998 | var db = new DBConnect();
1999 |
2000 | db.DoInform();
2001 | db.GetVersion();
2002 | db.DoLog();
2003 | db.Connect();
2004 | }
2005 | }
2006 | }
2007 | ```
2008 |
2009 | **Learn More:**
2010 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/
2011 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interface
2012 |
2013 | ### Namespaces
2014 |
2015 | **Namespaces** provide a way to group related top-level members into a hierarchy. They are also used to avoid naming conflicts. A top-level member, such as a class, that is not included in a namespace is said to belong to the **default namespace**. It can be moved to another namespace by being enclosed in a **namespace block**. You can use a namespace to organize code elements. You can define your own namespaces and use them in your program.
2016 |
2017 | **Properties Of Namespaces:**
2018 |
2019 | - They organize large code projects.
2020 | - They are delimited by using the ```.``` operator.
2021 | - The ```using``` keyword states that the program is using a given namespace.
2022 | - The global namespace is the "root" namespace: ```1global::System``` will always refer to the **.NET** System namespace.
2023 |
2024 | **Note 1:** The naming convention for namespaces is the same as for classes, with each word initially capitalized.
2025 | **Note 2:** The **.NET Framework** uses namespaces to organize its classes.
2026 |
2027 | ```csharp
2028 | namespace NamespaceDemonstration
2029 | {
2030 | class Program
2031 | {
2032 | static void Main(string[] args)
2033 | {
2034 | System.Console.WriteLine("Hello World!");
2035 | }
2036 | }
2037 | }
2038 | ```
2039 |
2040 | **Learn More:**
2041 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/namespaces/
2042 |
2043 | ### Operator Overloading
2044 |
2045 | **Operator overloading** allows operators to be **redefined** and used where one or both of the operands are of a certain class. When done correctly, this can simplify the code and make user-defined types as easy to use as the simple types.
2046 |
2047 | Overloaded operators are methods with special names, where the keyword ```operator``` is followed by the **symbol** for the operator being defined. Similar to any other method, an overloaded operator has a return type and a parameter list.
2048 |
2049 | ```csharp
2050 | using System;
2051 |
2052 | namespace OperatorOverloadDemonstration
2053 | {
2054 | class Program
2055 | {
2056 | class Box
2057 | {
2058 | public int Height { get; set; }
2059 | public int Width { get; set; }
2060 |
2061 | public Box(int h, int w) // The constructor of the class.
2062 | {
2063 | Height = h;
2064 | Width = w;
2065 | }
2066 |
2067 | public static Box operator+(Box a, Box b) // Overloading the + operator
2068 | {
2069 | int h = a.Height + b.Height;
2070 | int w = a.Width + b.Width;
2071 |
2072 | Box result = new Box(h, w);
2073 | return result;
2074 | }
2075 | }
2076 | static void Main(string[] args)
2077 | {
2078 | Box b1 = new Box(14, 3);
2079 | Box b2 = new Box(5, 7);
2080 | Box b3 = b1 + b2;
2081 |
2082 | Console.WriteLine(b3.Height);
2083 | Console.WriteLine(b3.Width);
2084 | }
2085 | }
2086 | }
2087 | ```
2088 |
2089 | **Learn More:**
2090 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading
2091 |
2092 | ---
2093 |
2094 | ## Delegates
2095 |
2096 | A **delegate** is a type used to reference a method. This allows methods to be assigned to variables and passed as arguments. The delegate’s declaration specifies the method signature to which objects of the delegate type can refer. Delegates are by convention named with each word initially capitalized, followed by Delegate at the end of the name.
2097 |
2098 | In other words, the delegate is a reference type data type that defines the method signature. You can define variables of delegate, just like other data type, that can refer to any method with the same signature as the delegate.
2099 |
2100 | **Note 1:** You can also pass delegates as parameters if needed.
2101 | **Note 2:** You can also define generic delegates in C#.
2102 | **Note 3:** In **.NET**, [```Func```](https://docs.microsoft.com/en-us/dotnet/api/system.func-1) and [```Action```](https://docs.microsoft.com/en-us/dotnet/api/system.action) types are built-in generic delegates that should be used for most common delegates instead of creating new custom ones.
2103 |
2104 | There are three steps involved while working with delegates:
2105 |
2106 | 1. Declare a delegate
2107 | 2. Set a target method
2108 | 3. Invoke a delegate
2109 |
2110 | **Delegate Syntax:**
2111 |
2112 | ```
2113 | [access modifier] delegate [return type] [delegate name]([parameters])
2114 | ```
2115 |
2116 | **Delegate Demonstration:**
2117 |
2118 | ```csharp
2119 | namespace DelegatesDemonstration
2120 | {
2121 | public delegate int MyDelegate(int x, int y);
2122 |
2123 | public class Program
2124 | {
2125 | static int Sum(int x, int y)
2126 | {
2127 | return x + y;
2128 | }
2129 |
2130 | public static void Main(string[] args)
2131 | {
2132 | // Simplified Syntax which was introduced in C# 2.0
2133 | MyDelegate delegateObject = Sum;
2134 |
2135 | // Execute the delegate object using the Invoke keyword
2136 | int result = delegateObject(12, 15);
2137 |
2138 | /* Alternative Syntax:
2139 |
2140 | MyDelegate delegateObject = new MyDelegate(Sum);
2141 | int result = delegateObject.Invoke(12, 15);
2142 |
2143 | */
2144 |
2145 | System.Console.WriteLine(result);
2146 | }
2147 | }
2148 | }
2149 | ```
2150 |
2151 | **Multicast Delegate Demonstration:**
2152 |
2153 | ```csharp
2154 | using System;
2155 |
2156 | public delegate void MyDelegate(string msg);
2157 |
2158 | public class ClassA
2159 | {
2160 | public static void MethodA(string message)
2161 | {
2162 | Console.WriteLine("Called ClassA.MethodA() with parameter: " + message);
2163 | }
2164 | }
2165 |
2166 | public class ClassB
2167 | {
2168 | public static void MethodB(string message)
2169 | {
2170 | Console.WriteLine("Called ClassB.MethodB() with parameter: " + message);
2171 | }
2172 | }
2173 |
2174 | public class Program
2175 | {
2176 | public static void Main(string[] args)
2177 | {
2178 | MyDelegate del1 = ClassA.MethodA;
2179 | MyDelegate del2 = ClassB.MethodB;
2180 |
2181 | MyDelegate del = del1 + del2;
2182 | Console.WriteLine("After del1 + del2");
2183 | del("Hello World");
2184 |
2185 | // Lambda expressions achieve the same goal as anonymous methods but with a concise syntax.
2186 | MyDelegate del3 = (string msg) => Console.WriteLine("Called lambda expression: " + msg);
2187 | del += del3;
2188 | Console.WriteLine("After del1 + del2 + del3");
2189 | del("Hello World");
2190 |
2191 | del = del - del2;
2192 | Console.WriteLine("After del - del2");
2193 | del("Hello World");
2194 |
2195 | del -= del1;
2196 | Console.WriteLine("After del1 - del1");
2197 | del("Hello World");
2198 | }
2199 | }
2200 | ```
2201 |
2202 | **Generic Delegate Demonstration:**
2203 |
2204 | ```csharp
2205 | using System;
2206 |
2207 | public delegate T GenericAdd(T param1, T param2);
2208 |
2209 | public class Program
2210 | {
2211 | public static int Sum(int val1, int val2)
2212 | {
2213 | return val1 + val2;
2214 | }
2215 |
2216 | public static string Concat(string str1, string str2)
2217 | {
2218 | return str1 + str2;
2219 | }
2220 |
2221 | public static void Main(string[] args)
2222 | {
2223 | GenericAdd mySum = Sum;
2224 | Console.WriteLine(mySum(10, 20));
2225 |
2226 | GenericAdd myConcat = Concat;
2227 | Console.WriteLine(myConcat("Hello ", "World!"));
2228 | }
2229 | }
2230 | ```
2231 |
2232 | **Built-in Delegates:**
2233 |
2234 | C# provides some built-in delegates that are useful for common purposes. These provide a shorthand notation that virtually eliminates the need to declare delegate types.
2235 |
2236 | **Examples:**
2237 |
2238 | - **Action**: used with methods that don’t return a value and have no parameter list.
2239 | - **Action<>**: used with methods that at least have one argument and don’t return a value.
2240 | - **Func<>**: used with methods that return a value and may have a parameter list.
2241 | - **Predicate<>**: represents a method that takes one input parameter and returns a bool value on the basis of some criteria.
2242 |
2243 | **Learn More:**
2244 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/
2245 | https://docs.microsoft.com/en-us/dotnet/api/system.delegate
2246 |
2247 | ### Anonymous Methods
2248 |
2249 | Anonymous methods are introduced in C# 2.0. They can be assigned to delegate objects. An anonymous method is specified by using the ```delegate``` keyword followed by a method parameter list and body. This can simplify the delegate’s instantiation since a separate method will not have to be defined in order to instantiate the delegate.
2250 |
2251 | ```csharp
2252 | delegate void MyDelegate(string str);
2253 |
2254 | public class Program
2255 | {
2256 | public static void Main(string[] args)
2257 | {
2258 | MyDelegate delegateObj = delegate(string s)
2259 | {
2260 | System.Console.WriteLine(s);
2261 | };
2262 |
2263 | delegateObj.Invoke("Hello World!");
2264 |
2265 | /* Alternative Syntax:
2266 | delegateObj("Hello World!");
2267 | */
2268 | }
2269 | }
2270 | ```
2271 |
2272 | **Learn More:**
2273 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/anonymous-functions
2274 |
2275 | ### Lambda Expressions
2276 |
2277 | Lambda expressions were introduced in C# 3.0. They achieve the same goal as anonymous methods, but with a more concise
2278 | syntax. A lambda expression is written as a parameter list followed by the lambda operator (=>) and an expression.
2279 |
2280 | ```csharp
2281 | namespace LambdaDemonstration
2282 | {
2283 | delegate int MyDelegate(int i);
2284 |
2285 | public class Program
2286 | {
2287 | public static void Main(string[] args)
2288 | {
2289 | // Anonymous Method
2290 | MyDelegate delegateObj1 = delegate(int x) { return x * x; };
2291 |
2292 | // Lambda expression
2293 | MyDelegate delegateObj2 = (int x) => x * x;
2294 |
2295 | System.Console.WriteLine(delegateObj1(5)); // 25
2296 | System.Console.WriteLine(delegateObj2(5)); // 25
2297 | }
2298 | }
2299 | }
2300 | ```
2301 |
2302 | **Learn More:**
2303 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions
2304 |
2305 | ---
2306 |
2307 | ## Events
2308 |
2309 | Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the **publisher** and the classes that receive (or handle) the event are called **subscribers**.
2310 |
2311 | Think of an event as an **encapsulated delegate**; It is dependent on the delegate. The delegate defines the signature for the event handler method of the subscriber class. It also avoids overwriting of a method reference by restricting the use of the assignment ```=``` operator.
2312 |
2313 | **Events Declaration:**
2314 |
2315 | - **Step 1:** Declare a delegate.
2316 | - **Step 2:** Declare a variable of the delegate with event keyword.
2317 |
2318 | **Basic Demonstration:**
2319 |
2320 | ```csharp
2321 | namespace EventDemonstration
2322 | {
2323 | public delegate string MyDelegate(string str); // Declare the delegate.
2324 |
2325 | public class EventClass
2326 | {
2327 | event MyDelegate MyEvent; // Declare a variable of the delegate with event keyword.
2328 |
2329 | public EventClass() // The constructor
2330 | {
2331 | // Register with an event
2332 | MyEvent += WelcomeUser;
2333 |
2334 | /* Alternative Syntax:
2335 | this.MyEvent += new MyDelegate(this.WelcomeUser);
2336 | */
2337 | }
2338 |
2339 | public string WelcomeUser(string username)
2340 | {
2341 | return "Welcome " + username;
2342 | }
2343 |
2344 | public static void Main(string[] args)
2345 | {
2346 | EventClass myObject = new EventClass();
2347 | System.Console.Write(myObject.MyEvent("Amy"));
2348 | }
2349 | }
2350 | }
2351 | ```
2352 |
2353 | **Notes:**
2354 |
2355 | - An event is a wrapper around a delegate. It depends on the delegate.
2356 | - Use "event" keyword with delegate type variable to declare an event.
2357 | - Use built-in delegate ```EventHandler``` or ```EventHandler``` for common events.
2358 | - The publisher class raises an event, and the subscriber class registers for an event and provides the event-handler method.
2359 | - Name the method which raises an event prefixed with "**On**" with the event name.
2360 | - The signature of the handler method must match the delegate signature.
2361 | - Register with an event using the ```+=``` operator.
2362 | - Unsubscribe an event using the ```-=``` operator.
2363 | - Pass event data using ```EventHandler```.
2364 | - Derive **EventArgs** base class to create custom event data class.
2365 | - Events can be declared ```static```, ```virtual```, ```sealed```, and ```abstract```.
2366 | - An **Interface** can include the event as a member.
2367 | - Event handlers are invoked **synchronously** if there are multiple **subscribers**.
2368 |
2369 | **Learn More:**
2370 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/
2371 |
2372 | ---
2373 |
2374 | ## Generics
2375 |
2376 | Generics introduce the concept of type parameters to .NET, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.
2377 |
2378 | ```csharp
2379 | using System;
2380 | using System.Collections.Generic;
2381 |
2382 | namespace Example
2383 | {
2384 | class Program
2385 | {
2386 | class Stack
2387 | {
2388 | int index = 0;
2389 | T[] innerArray = new T[100];
2390 |
2391 | public void Push(T item)
2392 | {
2393 | innerArray[index++] = item;
2394 | }
2395 |
2396 | public T Pop()
2397 | {
2398 | return innerArray[--index];
2399 | }
2400 |
2401 | public T Get(int k) { return innerArray[k]; }
2402 | }
2403 |
2404 | static void Main(string[] args)
2405 | {
2406 | // Defining a stack of integers
2407 | Stack intStack = new Stack();
2408 | intStack.Push(1);
2409 | intStack.Push(2);
2410 | intStack.Push(3);
2411 | Console.WriteLine(intStack.Get(1)); // Output => 2
2412 |
2413 | // Defining a stack of strings
2414 | Stack strStack = new Stack();
2415 | strStack.Push("Jane");
2416 | strStack.Push("James");
2417 | strStack.Push("John");
2418 | Console.WriteLine(strStack.Get(0)); // Output => Jane
2419 | }
2420 | }
2421 | }
2422 | ```
2423 |
2424 | **Learn More:**
2425 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/
2426 |
2427 | ---
2428 |
2429 | ## Generic Collections
2430 |
2431 | A collection is used to group related objects. Unlike an array, it is dynamic and can also group objects. A collection can grow and shrink to accommodate any number of objects. Collection classes are organized into namespaces and contain built in methods for processing elements within the collection.
2432 |
2433 | A collection organizes related data in a computer so that it can be used efficiently. Different kinds of collections are suited to different kinds of applications, and some are highly specialized to specific tasks.
2434 |
2435 | A collection typically includes methods to add, remove, and count objects. The ```for``` statement and the ```foreach``` statement are used to iterate through collections. Since a collection is a class you must first declare an instance of the class before you can add elements to that collection.
2436 |
2437 | **Learn More:**
2438 | https://docs.microsoft.com/en-us/dotnet/standard/generics/collections
2439 |
2440 | ### List
2441 |
2442 | A list is similar to an array, but the elements in a list can be inserted and removed dynamically. The C# generic collection ```List``` class requires all elements be of the same type ```T```.
2443 |
2444 | ```csharp
2445 | using System;
2446 | using System.Collections.Generic;
2447 |
2448 | namespace SampleList
2449 | {
2450 | class Program
2451 | {
2452 | static void Main(string[] args)
2453 | {
2454 | List liNumbers = new List();
2455 |
2456 | liNumbers.Add(59);
2457 | liNumbers.Add(72);
2458 | liNumbers.Add(95);
2459 | liNumbers.Add(5);
2460 | liNumbers.Add(9);
2461 | liNumbers.RemoveAt(1); // remove 72
2462 |
2463 | Console.Write("\nList: ");
2464 | for (int x = 0; x < liNumbers.Count; x++)
2465 | {
2466 | Console.Write($"{liNumbers[x]} "); // 59 95 5 9
2467 | }
2468 |
2469 | liNumbers.Sort();
2470 |
2471 | Console.Write("\nSorted: ");
2472 | for (int x = 0; x < liNumbers.Count; x++)
2473 | {
2474 | Console.Write($"{liNumbers[x]} "); // 5 9 59 95
2475 | }
2476 | }
2477 | }
2478 | }
2479 | ```
2480 |
2481 | **Learn More:**
2482 | https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1
2483 |
2484 | ### SortedList
2485 |
2486 | A sorted list is a collection of key/value pairs that are sorted by key. A key can be used to access its corresponding value in the sorted list.
2487 |
2488 | The C# generic collection ```SortedList``` class requires all element key/value pairs to be of the same type ```K```, ```V```. Duplicate keys are not permitted, which ensures that every key/value pair is unique.
2489 |
2490 | ```csharp
2491 | using System;
2492 | using System.Collections.Generic;
2493 |
2494 | namespace SampleSortedList
2495 | {
2496 | class Program
2497 | {
2498 | static void Main(string[] args)
2499 | {
2500 | SortedList slMarks = new SortedList();
2501 |
2502 | slMarks.Add("Jane", 70);
2503 | slMarks.Add("Kate", 30);
2504 | slMarks.Add("James", 90);
2505 | slMarks.Remove("Kate");
2506 |
2507 | Console.WriteLine("Sorted List: ");
2508 | foreach (string s in slMarks.Keys)
2509 | {
2510 | Console.WriteLine($"{s} : {slMarks[s]}"); // Jane: 70 James: 90
2511 | }
2512 |
2513 | Console.WriteLine($"Count: {slMarks.Count}"); // 2
2514 | }
2515 | }
2516 | }
2517 | ```
2518 |
2519 | **Learn More:**
2520 | https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedlist-2
2521 |
2522 | ### BitArray
2523 |
2524 | A bit array is a collection of bits. The value of a bit can be either 0 (off/false) or 1 (on/true). Bit arrays compactly store bits. Most commonly, they are used to represent a simple group of boolean flags or an ordered sequence of boolean values.
2525 |
2526 | ```csharp
2527 | using System;
2528 | using System.Collections;
2529 | using System.Collections.Generic;
2530 |
2531 | namespace SampleBitArray
2532 | {
2533 | class Program
2534 | {
2535 | // Printing BitArray
2536 | public static void PrintBarr(string name, BitArray ba)
2537 | {
2538 | Console.Write(name + " : ");
2539 |
2540 | for (int x = 0; x < ba.Length; x++)
2541 | {
2542 | Console.Write(ba.Get(x) + " ");
2543 | }
2544 |
2545 | Console.WriteLine();
2546 | }
2547 |
2548 | public static void Main(string[] args)
2549 | {
2550 | BitArray ba1 = new BitArray(4);
2551 | BitArray ba2 = new BitArray(4);
2552 |
2553 | ba1.SetAll(true);
2554 | ba2.SetAll(false);
2555 |
2556 | ba1.Set(2, false);
2557 | ba2.Set(3, true);
2558 |
2559 | PrintBarr("ba1", ba1);
2560 | PrintBarr("ba2", ba2);
2561 |
2562 | Console.WriteLine();
2563 | PrintBarr("ba1 AND ba2", ba1.And(ba2));
2564 | PrintBarr("NOT ba2", ba2.Not());
2565 | }
2566 | }
2567 | }
2568 | ```
2569 |
2570 | **Learn More:**
2571 | https://docs.microsoft.com/en-us/dotnet/api/system.collections.bitarray
2572 |
2573 | ### Stack
2574 |
2575 | A stack is a Last In, First Out (LIFO) collection of elements where the last element that goes into the stack will be the first element that comes out.
2576 |
2577 | Inserting an element onto a stack is called pushing. Deleting an element from a stack is called popping. Pushing and popping can be performed only at the top of the stack.
2578 |
2579 | Stacks can be used to create undo-redo functionalities, parsing expressions (infix to postfix/prefix conversion), and much more.
2580 |
2581 | The C# generic collection ```Stack``` class requires all elements to be of the same type ```T```.
2582 |
2583 | ```csharp
2584 | using System;
2585 | using System.Collections.Generic;
2586 |
2587 | namespace SampleStack
2588 | {
2589 | class Program
2590 | {
2591 | static void Main(string[] args)
2592 | {
2593 | Stack s = new Stack();
2594 |
2595 | s.Push(59);
2596 | s.Push(72);
2597 | s.Push(65);
2598 |
2599 | Console.Write("Stack: ");
2600 | foreach (int i in s)
2601 | {
2602 | Console.Write(i + " "); // 65 72 59
2603 | }
2604 |
2605 | Console.WriteLine($"\nCount: {s.Count}"); // 3
2606 | Console.WriteLine($"Top: {s.Peek()}"); // 65
2607 | Console.WriteLine($"Pop: {s.Pop()}"); // 65
2608 |
2609 | Console.Write("\nStack: ");
2610 | foreach (int i in s)
2611 | {
2612 | Console.Write(i + " "); // 72 59
2613 | }
2614 | Console.WriteLine($"\nCount: {s.Count}"); // Count: 2
2615 | }
2616 | }
2617 | }
2618 | ```
2619 |
2620 | **Learn More:**
2621 | https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1
2622 |
2623 | ### Queue
2624 |
2625 | A queue is a First In, First Out (FIFO) collection of elements where the first element that goes into a queue is also the first element that comes out.
2626 |
2627 | Inserting an element into a queue is referred to as Enqueue. Deleting an element from a queue is referred to as Dequeue. Queues are used whenever we need to manage objects in order starting with the first one in.
2628 |
2629 | The C# generic collection ```Queue``` class requires that all elements be of the same type ```T```.
2630 |
2631 | ```csharp
2632 | using System;
2633 | using System.Collections.Generic;
2634 |
2635 | namespace SampleQueue
2636 | {
2637 | class Program
2638 | {
2639 | static void Main(string[] args)
2640 | {
2641 | Queue q = new Queue();
2642 |
2643 | q.Enqueue(5);
2644 | q.Enqueue(10);
2645 | q.Enqueue(15);
2646 |
2647 | Console.Write("Queue: ");
2648 | foreach (int i in q)
2649 | {
2650 | Console.Write(i + " "); // 5 10 15
2651 | }
2652 |
2653 | Console.WriteLine($"\nCount: {q.Count} \n"); // Count: 3
2654 | Console.WriteLine($"Dequeue: {q.Dequeue()} \n"); // Dequeue: 5
2655 |
2656 | Console.Write("Queue: ");
2657 | foreach (int i in q)
2658 | {
2659 | Console.Write(i + " "); // Queue: 10 15
2660 | }
2661 | Console.WriteLine($"\nCount: {q.Count}"); // Count: 2
2662 | }
2663 | }
2664 | }
2665 | ```
2666 |
2667 | **Learn More:**
2668 | https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.queue-1
2669 |
2670 | ### Dictionary
2671 |
2672 | A dictionary is a collection of unique key/value pairs where a key is used to access the corresponding value. Dictionaries are used in database indexing, cache implementations, and so on.
2673 |
2674 | The C# generic collection ```Dictionary``` class requires all key/value pairs be of the same type ```K```, ```V```. Duplicate keys are not permitted to ensure that every key/value pair is unique.
2675 |
2676 | ```csharp
2677 | using System;
2678 | using System.Collections.Generic;
2679 |
2680 | namespace SampleDictionary
2681 | {
2682 | class Program
2683 | {
2684 | static void Main(string[] args)
2685 | {
2686 | Dictionary d = new Dictionary();
2687 |
2688 | d.Add("Uno", 1);
2689 | d.Add("Dos", 2);
2690 | d.Add("Tres", 3);
2691 |
2692 | d.Remove("Tres"); // Remove key-value pair Tres, 3
2693 |
2694 | Console.WriteLine("Dictionary: ");
2695 | foreach (string s in d.Keys)
2696 | {
2697 | Console.Write($"{s} : {d[s]} "); // Uno: 1 Dos: 2
2698 | }
2699 | Console.WriteLine($"\nCount: {d.Count}"); // Count: 2
2700 | }
2701 | }
2702 | }
2703 | ```
2704 |
2705 | **Learn More:**
2706 | https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2
2707 |
2708 | ### HashSet
2709 |
2710 | A hash set is a set of unique values where duplicates are not allowed.
2711 |
2712 | C# includes the ```HashSet``` class in the generic collections namespace. All ```HashSet``` elements are required to be of the same type ```T```.
2713 |
2714 | Hash sets are different from other collections because they are simply a set of values. They do not have index positions and elements cannot be ordered.
2715 |
2716 | The ```HashSet``` class provides high-performance set operations. HashSets allow fast lookup, addition, and removal of items, and can be used to implement either dynamic sets of items or lookup tables that allow finding an item by its key.
2717 |
2718 | ```csharp
2719 | using System;
2720 | using System.Collections.Generic;
2721 |
2722 | namespace SampleHashSet
2723 | {
2724 | class Program
2725 | {
2726 | static void Main(string[] args)
2727 | {
2728 | HashSet hs = new HashSet();
2729 |
2730 | hs.Add(5);
2731 | hs.Add(10);
2732 | hs.Add(15);
2733 | hs.Add(20);
2734 |
2735 | Console.Write("HashSet: ");
2736 | foreach (int i in hs)
2737 | {
2738 | Console.Write(i + " ");
2739 | }
2740 | Console.WriteLine($"\nCount: {hs.Count}"); // Count: 4
2741 |
2742 | HashSet hs2 = new HashSet();
2743 | hs2.Add(15);
2744 | hs2.Add(20);
2745 | Console.WriteLine("{15, 20} is a subset of {5, 10, 15, 20} : " + hs2.IsSubsetOf(hs));
2746 | }
2747 | }
2748 | }
2749 | ```
2750 |
2751 | **Learn More:**
2752 | https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1
2753 |
2754 | ---
2755 |
2756 | ## Constants
2757 |
2758 | ### The ```const``` Keyword
2759 |
2760 | A variable in C# can be made into a compile-time constant by adding the ```const``` keyword before the data type. This modifier means that the variable cannot be changed and it must therefore be assigned a value at the same time as it is declared. Any attempts to assign a new value to the constant will result in a compile-time error.
2761 |
2762 | ```csharp
2763 | static void Main(string[] args)
2764 | {
2765 | const double Pi = 3.14159265358979323846; // compile-time constant
2766 | }
2767 | ```
2768 |
2769 | **Note:** Constant fields cannot have the static modifier. They are implicitly static and are accessed in the same way as static fields.
2770 |
2771 | ### The ```readonly``` Keyword
2772 |
2773 | Another variable modifier similar to ```const``` is ```readonly```. It creates a runtime constant. This modifier can be applied to fields, and like ```const```, it makes the field unchangeable.
2774 |
2775 | **Note 1:** Unlike const, ```readonly``` can be applied to any data type.
2776 |
2777 | **Note 2:** a ```readonly``` field cannot only be initialized when it is declared. It can also be assigned a value in the constructor.
2778 |
2779 | **Note 3:** Since a ```readonly``` field is assigned at runtime, it can be assigned a dynamic value that is not known until runtime.
2780 |
2781 | **Note 4:** You can also mark a method’s return value as ```readonly``` when returning a value type by reference with the ```ref``` modifier. This will disallow the caller from modifying the returned value, provided that the returned value is also assigned as a readonly reference and not just a copy.
2782 |
2783 | ```csharp
2784 | class MyClass
2785 | {
2786 | readonly static int i;
2787 |
2788 | static ref readonly int GetValue()
2789 | {
2790 | return ref i;
2791 | }
2792 |
2793 | static void Main(string[] args)
2794 | {
2795 | ref readonly int myValue = ref GetValue();
2796 | }
2797 | }
2798 | ```
2799 |
2800 | **Learn More:**
2801 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constants
2802 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/const
2803 |
2804 | ---
2805 |
2806 | ## Asynchronous Methods
2807 |
2808 | An asynchronous method is a method that can **return** before it has finished executing. Any method that performs a potentially long-running task, such as accessing a web resource or reading a file, can be made asynchronous to improve the responsiveness of the program.
2809 |
2810 | The ```async``` and ```await``` keywords allow asynchronous methods to be written with a simple structure that is similar to synchronous (regular) methods. The ```async``` modifier specifies that the method is asynchronous and that it can therefore contain one or more ```await``` expressions. An ```await``` expression consists of the ```await``` keyword followed by an awaitable method call.
2811 |
2812 | ```csharp
2813 | class MyApp
2814 | {
2815 | async void MyAsync()
2816 | {
2817 | System.Console.Write("A");
2818 | await System.Threading.Tasks.Task.Delay(2000);
2819 | System.Console.Write("C");
2820 | }
2821 | }
2822 |
2823 | static void Main(string[] args)
2824 | {
2825 | new MyApp().MyAsync();
2826 | System.Console.Write("B");
2827 |
2828 | // Outputs: ABC
2829 | System.Console.ReadKey(); // Prevents the console program from exiting before the async method has finished.
2830 | }
2831 | ```
2832 |
2833 | **Learn More:**
2834 | https://docs.microsoft.com/en-us/dotnet/csharp/async
2835 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/
2836 |
2837 | ---
2838 |
2839 | ## Working With Files
2840 |
2841 | The System.IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file, and more. The File class is one of them.
2842 |
2843 | Popular methods of the File class:
2844 |
2845 | - **AppendAllText()** : Appends text to the end of the file.
2846 | - **Create()** : Creates a file in the specified location.
2847 | - **Delete()** : Deletes the specified file.
2848 | - **Exists()** : Determines whether the specified file exists.
2849 | - **Copy()** : Copies a file to a new location.
2850 | - **Move()** : Moves a specified file to a new location
2851 |
2852 | ```csharp
2853 | using System;
2854 | using System.IO;
2855 |
2856 | namespace Example
2857 | {
2858 | class Program
2859 | {
2860 | static void Main(string[] args)
2861 | {
2862 | string str = "Working with files in C#";
2863 | File.WriteAllText("example.txt", str);
2864 |
2865 | string txt = File.ReadAllText("example.txt");
2866 | Console.WriteLine(txt);
2867 | }
2868 | }
2869 | }
2870 | ```
2871 |
2872 | **Learn More:**
2873 | https://docs.microsoft.com/en-us/dotnet/api/system.io.file
2874 |
2875 | ---
2876 |
2877 | ## Language-Integrated Query (LINQ)
2878 |
2879 | Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.
2880 |
2881 | ```csharp
2882 | class LINQQueryExpressions
2883 | {
2884 | static void Main()
2885 | {
2886 | // Specify the data source.
2887 | int[] scores = new int[] { 97, 92, 81, 60 };
2888 |
2889 | // Define the query expression.
2890 | IEnumerable scoreQuery =
2891 | from score in scores
2892 | where score > 80
2893 | select score;
2894 |
2895 | // Execute the query.
2896 | foreach (int i in scoreQuery)
2897 | {
2898 | Console.Write(i + " ");
2899 | }
2900 | }
2901 | }
2902 | // Output: 97 92 81
2903 | ```
2904 |
2905 | **Learn More:**
2906 | https://docs.microsoft.com/en-us/dotnet/csharp/linq/
2907 | https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/working-with-linq
2908 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
2909 |
2910 | ---
2911 |
2912 | ## Attributes
2913 |
2914 | An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to a program by using an attribute. A declarative tag is depicted by square ([ ]) brackets placed above the element it is used for.
2915 |
2916 | Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods and classes to a program.
2917 |
2918 | There are two types of Attributes implementations provided by the .NET Framework are:
2919 |
2920 | - Predefined Attributes
2921 | - Custom Attributes
2922 |
2923 | ### Predefined Attributes
2924 |
2925 | Predefined attributes are those attributes that are a part of the .NET Framework Class Library and are supported by the C# compiler for a specific purpose.
2926 |
2927 | A few popular predefined attributes that are derived from the ```System.Attribute``` base class are given as follows:
2928 |
2929 | | Attribute | Description |
2930 | | --------------------------- | ------------------------------------------------------------ |
2931 | | AttributeUsageAttribute | Specifies the usage of a different attribute. |
2932 | | CLSCompliantAttribute | Shows if a particular code element complies with the Common Language Specification |
2933 | | ContextStaticAttribute | Indicates if a static field value is unique for the specified context |
2934 | | FlagsAttribute | Indicates if a static field value is unique for the specified context |
2935 | | LoaderOptimizationAttribute | Sets the optimization policy for the default loader in the main method |
2936 | | NonSerializedAttribute | Signifies that the field of the serializable class should not be serialized |
2937 | | ObsoleteAttribute | Marks the code elements that are obsolete i.e. not in use anymore |
2938 | | SerializableAttribute | Signifies that the field of the serializable class can be serialized |
2939 | | ThreadStaticAttribute | Indicates that there is a unique static field value for each thread |
2940 | | DllImportAttribute | Indicates that the method is a static entry point as shown by the unmanaged DLL |
2941 |
2942 | ```csharp
2943 | // C# program to demonstrate CLSCompliantAttribute giving a warning message
2944 | using System;
2945 |
2946 | // CLSCompliantAttribute applied to entire assembly
2947 | [assembly:CLSCompliant(true)]
2948 |
2949 | public class GFG
2950 | {
2951 | public uint z;
2952 | }
2953 |
2954 | class GFG2
2955 | {
2956 | public static void Main(string[] args)
2957 | {
2958 | Console.WriteLine("Demonstrating the CLSCompliantAttribute");
2959 | }
2960 | }
2961 | ```
2962 |
2963 | ### Custom Attributes
2964 |
2965 | Custom attributes can be created in C# for attaching declarative information to methods, assemblies, properties, types, etc. in any way required. This increases the extensibility of the .NET framework.
2966 |
2967 | ```csharp
2968 | // C# program to demonstrate Custom Attributes
2969 | using System;
2970 |
2971 | // AttributeUsage specifies the usage of InformationAttribute
2972 | [AttributeUsage(AttributeTargets.Class |
2973 | AttributeTargets.Constructor |
2974 | AttributeTargets.Method, AllowMultiple = true)]
2975 |
2976 | // InformationAttribute is a custom attribute class that is derived from Attribute class
2977 | class InformationAttribute : Attribute
2978 | {
2979 | public string InformationString{ get; set; }
2980 | }
2981 |
2982 | // InformationAttribute is used in student class
2983 | [Information(InformationString = "Class")] public class student
2984 | {
2985 | private int rollno;
2986 | private string name;
2987 |
2988 | [Information(InformationString = "Constructor")] public student(int rollno, string name)
2989 | {
2990 | this.rollno = rollno;
2991 | this.name = name;
2992 | }
2993 |
2994 | [Information(InformationString = "Method")] public void display()
2995 | {
2996 | Console.WriteLine($"Roll Number: {rollno}");
2997 | Console.WriteLine($"Name: {name}");
2998 | }
2999 | }
3000 |
3001 | public class GFG
3002 | {
3003 | public static void Main(string[] args)
3004 | {
3005 | student s = new student(1001, "Jane Doe");
3006 | s.display();
3007 | }
3008 | }
3009 | ```
3010 |
3011 | **Learn More:**
3012 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/
3013 |
3014 | ### Extension Methods
3015 |
3016 | Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
3017 |
3018 | The following example shows an extension method defined for the System.String class:
3019 |
3020 | ```csharp
3021 | namespace ExtensionMethods
3022 | {
3023 | public static class MyExtensions
3024 | {
3025 | public static int WordCount(this string str)
3026 | {
3027 | return str.Split(new char[] { ' ', '.', '?' },
3028 | StringSplitOptions.RemoveEmptyEntries).Length;
3029 | }
3030 | }
3031 | }
3032 | ```
3033 |
3034 | It can be called from an application by using this syntax:
3035 |
3036 | ```csharp
3037 | string s = "Hello Extension Methods";
3038 | int i = s.WordCount();
3039 | ```
3040 |
3041 | **Learn More:**
3042 | https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
3043 |
3044 | ---
3045 |
3046 | ## References
3047 |
3048 | **Official C# Documentation:**
3049 | https://docs.microsoft.com/en-us/dotnet/csharp/
3050 |
3051 | **Official C# Language Reference:**
3052 | https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/
3053 |
3054 | **Official Unity User Manual:**
3055 | https://docs.unity3d.com/Manual/index.html
3056 |
3057 | ---
3058 |
3059 | ## Credits
3060 |
3061 | **Prepared By:**
3062 |
3063 | - [ConstructG.com](https://constructg.com)
3064 | - [Labinator.com](https://labinator.com)
3065 |
3066 | **Based On:**
3067 |
3068 | - This guide has used several examples and definitions from the [Microsoft's .NET documentation](https://docs.microsoft.com/en-us/dotnet/).
3069 |
--------------------------------------------------------------------------------