0% found this document useful (0 votes)
28 views154 pages

C - Become A Master in C (C Programming Language, C - Dorsey, Richard

This document is an eBook about C#, covering its history, environment, and programming structure. It emphasizes that the information provided is for entertainment purposes only and should not be considered expert advice. The book includes various chapters detailing C# features, syntax, and development tools, aiming to equip readers with the knowledge to write programs in C#.

Uploaded by

surajyadavkafa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views154 pages

C - Become A Master in C (C Programming Language, C - Dorsey, Richard

This document is an eBook about C#, covering its history, environment, and programming structure. It emphasizes that the information provided is for entertainment purposes only and should not be considered expert advice. The book includes various chapters detailing C# features, syntax, and development tools, aiming to equip readers with the knowledge to write programs in C#.

Uploaded by

surajyadavkafa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 154

© Copyright 2017 by Richard Dorsey - All rights reserved.

The follow eBook is reproduced below with the goal of providing


information that is as accurate and reliable as possible. Regardless,
purchasing this eBook can be seen as consent to the fact that both the
publisher and the author of this book are in no way experts on the topics
discussed within and that any recommendations or suggestions that are made
herein are for entertainment purposes only. Professionals should be consulted
as needed prior to undertaking any of the action endorsed herein.
This declaration is deemed fair and valid by both the American Bar
Association and the Committee of Publishers Association and is legally
binding throughout the United States.
Furthermore, the transmission, duplication or reproduction of any of the
following work including specific information will be considered an illegal
act irrespective of if it is done electronically or in print. This extends to
creating a secondary or tertiary copy of the work or a recorded copy and is
only allowed with express written consent from the Publisher. All additional
right reserved.
The information in the following pages is broadly considered to be a truthful
and accurate account of facts and as such any inattention, use or misuse of the
information in question by the reader will render any resulting actions solely
under their purview. There are no scenarios in which the publisher or the
original author of this work can be in any fashion deemed liable for any
hardship or damages that may befall them after undertaking information
described herein.
Additionally, the information in the following pages is intended only for
informational purposes and should thus be thought of as universal. As
befitting its nature, it is presented without assurance regarding its prolonged
validity or interim quality. Trademarks that are mentioned are done without
written consent and can in no way be considered an endorsement from the
trademark holder.
TABLE OF CONTENTS

Introduction
Chapter One: An Overview of C#
Chapter Two: The History of C#
Chapter Three: C# Environment
Chapter Four: The Program Structure of C#
Chapter Five: C# Syntax
Chapter Six: Data Classes
Chapter Seven: Class Conversion in C#
Chapter Eight: The Variables Found in C#
Chapter Nine: C# Constants and Literals
Chapter Ten: C# Operators
Chapter Eleven: Decision Making with C#
Chapter Twelve: Loops
Chapter Thirteen: Encapsulation in C#
Chapter Fourteen: Methods That Are Used in C#
Chapter Fifteen: Nullables Found in C#
Chapter Sixteen: Arrays Found in C#
Chapter Seventeen: Strings in C#
Chapter Eighteen: C# Structures
Chapter Nineteen: Enums in C#
Chapter Twenty: Classes You Find in C#
Conclusion
INTRODUCTION

C ongratulations on downloading C# and thank you for doing so.


The following chapters will discuss everything you need to know about C#.
By the time that you finish this book, you should be able to use C# to write
programs and interact with a computer on the proper level for that language.
C# is going to be similar to other C languages, but you are going to realize
that there are some differences that make it its own unique language.
There are plenty of books on this subject on the market, thanks again for
choosing this one! Every effort was made to ensure it is full of as much
useful information as possible, please enjoy!
CHAPTER ONE
AN OVERVIEW OF C#

W henever you begin to use C#, you are going to notice that it is a
language that is object oriented that was created by the Microsoft
company and then approved by the ECMA (European Computer
Manufacturers Association) as well as the ISO (International Standards
Organization).
Anders Hejlsberg developed the language while his team worked on
developing the .Net framework that goes with it. It was designed to be used
with CLI (Common Language Infrastructures) which are going to show you
the code that can be performed along with the runtime environment that is
going to allow for you to use an elevated level on various platform and
architectures.
Some of the reasons that make C# a widely used language are:
1. You can use it as part of the .Net framework
2. It is a general-purpose programming language
3. You can use it across a variety of platforms
4. It is an object-oriented program
5. It is going to produce programs that are efficient
6. It is component oriented
7. The language is structured and easy to learn
While it may seem that C# is nothing more than another variation of the C
programming language, it is going to resemble Java more than it will C due
to the fact that it is a program that is used by programmers all over the world.
Some of the features that programmers find important are:
1. It can be integrated with Windows
2. Boolean conditions
3. Expressions for LINQ and Lambda
4. Automatic garbage collection
5. Multithreading made simple
6. Standard library
7. Conditional compilation
8. Assembly variations
9. Indexers
10. Properties and events
11. Easy to use Generics
12. Delegates and event management
CHAPTER TWO
THE HISTORY OF C#

W henever the .Net framework was being developed, the class libraries
were written with managed code compilers in a system known as
Simple Managed C. it was not until January of 99 that Hejlsberg builds a
team that built the new language which was called Cool for short but was
really C like Object Oriented Language. It was then that Microsoft had
thought about using Cool as the final name for their project, however, did not
due to copyright reasons.
The .Net project was announced to the Open in 2000 at the Professional
Developers Conference that the language with the new name of C# and the
class libraries were given the name ASP. Net while runtime was ported into
the language.
The principal designer of the C# language was also the head architect at
Microsoft and had been involved in creating the design for Turbo Pascal,
Embarcadero Delphi which used to be known as CodeGear Delphi Inpris
Delphi and BorlandDelphi as well as working with Visual J++. When sitting
through interviews and papers that were written, Hejlsberg said that the flaws
that could be found in most of the programming languages would be what
drove the fundamentals for the Common Language Runtime which then
drove the design for the language itself.
In 94, James Gosling created the Java language, and Bill Joy who was the co-
founder for Sun Microsystems said that C# was just an imitation of the Java
language. He even went as far to say, “C# is sort of Java with reliability,
productivity, ad security deleted.” Kreft and Langer came back saying that
“Java and C# are almost identical programming languages. Boring repetition
that lacks innovation. Hardly anybody will claim that Java or C# are
revolutionary programming languages that changed the way we write
programs. And, C# borrowed a lot from Java and vice versa. Now that C#
supports boxing and unboxing, we will have a very similar feature in Java.”
Later in 2000 Hejlsberg stepped up and said, “C# is not a Java clone and is
much closer to C++ in its design.”
Ever since variation 2.0 was released in 2005, C# and Java evolved on
different trajectories which made them less similar than the other. One of the
biggest differences was the addition of generics to the languages which made
them different from each other. C# uses reification in order to offer first class
generic objects that have the ability to be used in other classes as the code is
generated to perform at class load time. Along with that, C# has features that
make it to where it is a functional style programming language that works
with the LINQ extensions that were released with variation 3.0 of C#.
Here are the features that were added in each variation of C# as they were
released.
VARIATION 2.0
1. Delegate inference
2. Generics
3. Static classes
4. Partial classes
5. Co and contravariance for delegates
6. Anonymous methods
7. Method group conversations
8. Iterators
9. Getter/ setter separate accessibility
10. Nullable class
VARIATION 3.0
1. Partial methods
2. Implicitly class local variables
3. Expression trees
4. Object and collection initializers
5. Lambda expression
6. Auto-implemented properties
7. Query expressions
8. Anonymous classes
9. Extension methods
VARIATION 4.0
1. Embedded Interop classes
2. Dynamic binding
3. Generic co and contravariance
4. Named and optional arguments
VARIATION 5.0
1. Caller info attributes
2. Asynchronous methods
VARIATION 6.0
1. Dictionary initializer
2. Compiler as a service
3. Name of operator
4. Import of static class members into namespace
5. String interpolation
6. Exception filters
7. Null propagator
8. Await in catch/ finally blocks
9. Expression-bodied members
10. Auto property initializers
11. Default values for getter only properties
VARIATION 7.0
1. Expression-bodied getters and setters
2. Out variables
3. Expression-bodied constructors and finalizers
4. Pattern matching
5. Generalized async return class
6. Tuples
7. Ref returns and locals
8. Deconstruction
9. Binary literals
10. Local functions
11. Digit separators
VARIATION 7.1
1. Default expressions
2. Async main
CHAPTER THREE
C# ENVIRONMENT

.N et is a framework that runs on its own platform that is going to assist


you in writing windows applications, web services, and web applications.
This framework has applications that are going to work across multiple
platforms due to the fact that the framework is designed to be used with
almost any programming language. Each language has the option of
accessing the framework so that they can communicate with each other.
The .Net framework works with a library full of codes that you are going to
be able to use with C#. Some of the components for the .Net framework are:
1. LINQ
2. CLR (Common Language Runtime)
3. WCF (Windows Communication Foundation)
4. The .Net Framework Class Library
5. Windows Presentation Foundation
6. Common Language Specification
7. WF (Windows Workflow Foundation)
8. Common Class System
9. ADO. Net
10. Metadata and Assemblies
11. ASP. NET and ASP. Net AJAX
12. Windows Forms
Each component is going to perform a different job that you are going to be
able to look at either by using the component or by looking at the
documentation that is offered by Microsoft.
INTEGRATED DEVELOPMENT ENVIRONMENT
There are more development tools that you are going to be able to use just
with C Sharp and those tools are
1. Visual Web creator
2. VS (Visual Studio 2010)
3. VCE (Visual C# 2010 Express)
The web creator and the VCE are going to be found on the official website
for Microsoft. When you are using these tools, you are going to have the
ability to write almost any kind of C# program. You will also have the option
of writing source code files that are going to work with basic text editors such
as Notepad so that you can mold the code into assemblies while using the
command prompt which is going to be part of the .Net Framework.
VCE and the web creator are going to be variations that are smaller than the
visual studio and are going to contain the same appearance as it.
You need to have a stable connection when you are installing the express
edition of the visual studio.
WRITING PROGRAMS ON LINUX AND MAC
Being that the .Net framework is a Windows system software function; there
are other variations that you are going to be able to use when you are working
with other system software s. Mono is a variation of the .Net framework
which going to work with the C# compiler and run on several different
system software s such as Linux and Mac OS.
The whole purpose behind Mono is to be able to run applications that are
built for Microsoft .Net in order to make them work with tools that were
developed for other system software s such as Android, iOS, Linux, and
Unix.
CHAPTER FOUR
THE PROGRAM STRUCTURE OF C#

B efore you are able to learn what, it takes to build a C# program, you are
going to have to look at how the programming language is built.
There are certain parts of the program that are going to be vital for ensuring
that you are adding them for when you are creating a C# program.
1. Comments
2. Namespace declaration
3. Statements and expressions
4. A class
5. The main method
6. Class methods
7. Class attributes
Example
Using system;
Namespace helloouterspaceapplication
{
Class helloouterspace
Static void main (tuple [] para)
{
/* your first C # program */
Console. Write line (“hello outer space”);
Console. Ready key ();
}
}
}
Once the code has been performd, you are going to get a result of “Hello
outer space”
The first line in your programming is going to be the using system part of the
code. The using keyword is going to include the namespace of a system for
the program. Most C# programs use multiple using statements.
Your namespace declaration is going to be the collection of classes that you
are using. The name of your application is going to be the class for that
application.
Your declaration for your class is going to hold all of the data and definitions
that the program is ultimately going to use. Classes are going to contain
multiple methods, and these methods are going to end up defining the
behavior for the class. But, the class that was used in the example only has
one method known as main.
Your main method is going to be where all of the C# programs enter. This
method is going to state when the class is going to be performed.
The asterisks and the slashes are going to be ignored by the compiler due to
the fact that they are comments on the program.
Your main method is going to tell you what behavior your statement is going
to follow.
Write line is the method that will be used by the console class when spelled
out in the namespace. This is the statement that is going to cause your result
to show up on the screen in front of you,
The bottom line is going to be for the VS. Net users. This is going to cause
the program to wait until a key is pressed which is ultimately going to stop
your page from opening and closing whenever the program is started from
the visual studio.
Some things that you are going to want to keep in mind are:
1. The file name has to be different from the class name
2. C # is case sensitive
3. Your execution is going to start at the main method
4. All your statements and expressions have to end with a semicolon
COMPILING AND PERFORMING YOUR
PROGRAM
If you are going to be using the .Net for Visual Studio, you are going to need
to take these steps.
1. You need to open up your visual studio
2. Moving to the menu bar you are going to go to file, new, project.
3. Choose a template and then select Windows
4. Go to the console application
5. Pick what you want to name your project
6. Your new project is going to be created in the solution explorer
7. Now you will write out your code with the code editor.
8. Select the run button in order to carry out your project. The command
prompt is going to appear and will display your output.
When you are compiling a program with C# with the command line rather
than using visual studio you are going to follow these steps.
1. Select your favorite text editor and insert the code you are going to be
using
2. Save the file with your file name and add the suffix of .cs
3. The command prompt needs to be opened so that you can locate the
directory that holds your file.
4. Enter CSC and the name of your file before pressing enter to force your
code to be compiled.
5. In the event that you have no errors, the next line is going to be brought
to your attention which is going to be the line that generates your
executable file.
6. Enter your code to perform the program
7. Your output should be printed on your screen.
CHAPTER FIVE
C# SYNTAX

B eing that C# is an object-oriented programming language, there are


going to be objects that you are going to have to use in order to interact
with other objects so that you create actions. These actions are going to create
methods whenever they are used. Objects that are the same are going to have
class or will be in the same class.
Think of a rectangle for example. The length and width are going to be the
attributes for the rectangle. Depending on the design of the rectangle the
values are accepted for those attributes while calculating the area and
displaying the details.
Example:
Using system;
Namespace circle application
{
Class circle
{
// variables
Double width;
Double circumference
Open void accept details ()
{
Width = 3. 4
Circumference = 3.2
}
Open double ()
{
Return width * circumference
}
Open void display ()
{
Console. WriteLine (“width: {0}”, width);
Console. WriteLine (circumference: {0}, circumference);
}
}
Class perform circle
{
Static void main (string [] para)
{
Circle c = new circle ();
C accept details ();
C. display ();
Console. ReadiLine ();
}
}
}
For the example shown above, you are going to the measurements for the
circle.
Using
In C# your first statement is always using system;
The keyword using is used for namespaces in C#.
Class
You will use this keyword when you are declaring your class.
Comments
You will use comments whenever you have to explain the code you have
created. Your C# compilers are going to ignore any comments that you make.
A multiple line comment is going to start like this /* and end like this */.
A single line comment will use a set of double slashes.
Member variables
These variables are going to be the attributes of the members of a class.
When used they can store data.
Member functions
The member functions are the statements that are going to carry out the task.
These functions for classes are typically declared inside of the class.
Instantiating a class
A class is going to contain the name of the class in the main method of the
script.
Identifiers
Identifiers are going to be words that you use to identify classes, variables,
and functions. There are three rules for creating identifiers in C#.
1. You cannot use a keyword that you find in C#
2. You have to start your word with a letter and then follow it with other
letters, digits, or underscores. But you cannot start with a digit.
3. You cannot use any special characters but an underscore.
Keywords in C#
The keywords are going to be words that are reserved by the compiler in C#.
These keywords are going to be set to where they cannot be used as
identifiers. But, if you want to use these words for your identifier, you are
going to be able to use an at symbol before the word in order to make it valid
in C#.
The identifiers found in C# are going to hold special meanings in your code
which causes some to be called contextual keywords.
Reserved keywords
1. Abstract
2. Catch
3. Default
4. Explicit
5. Foreach
6. Interface
7. Null
8. Private
9. Sealed
10. Switch
11. Ulong
12. Volatile
13. While
14. Unchecked
15. This
16. Short
17. Protected
18. Object
19. Internal
20. Goto
21. Extern
22. Delegate
23. Char
24. As
25. Base
26. Checked
27. Do
28. False
29. If
30. Is
31. Operator
32. Open
33. Sizeof
34. Throw
35. Unsafe
36. Ushort
37. True
38. Stackalloc
39. Readonly
40. Out
41. Lock
42. Implicit
43. Finally
44. Double
45. Class
46. Bool
47. Break
48. Const
49. Else
50. Fixed
51. In
52. Long
53. Out
54. Ref
55. Static
56. Try
57. Using
58. Virtual
59. Classof
60. String
61. Return
62. Override
63. Namespace
64. In
65. Float
66. Enum
67. Continue
68. Byte
69. Case
70. Decimal
71. Event
72. For
73. Int
74. New
75. Params
76. Sbyte
77. Struct
78. Uint
79. Void
Contextual keywords
1. Partial
2. Get
3. From
4. Orderby
5. Let
6. Dynamic
7. Set
8. Join
9. Descending
10. Ascending
11. Into
12. Select
13. Remove
14. Group
15. Alias
16. Partial
17. Global
18. Add
CHAPTER SIX
DATA CLASSES

T here are three different data classes in C#.


1. Pointer
2. Value
3. Reference
VALUE CLASSES
The value class is going to be the variables that you will assign to your value
directly. These are going to be derived from system.value. class.
The value class is going to contain data directly such as char, int, and float.
Whenever a int class is declared the system is going to make room for it.
Value classes:
1. Bool: Boolean values
2. Byte: 8 bit unsigned integers
3. Char: 16 bit Unicode characters
4. Decimal: 128 bit precise decimal values with up to 29 significant digits
5. Double: 64-bit double floating point class
6. Float: 32-bit single floating point class
7. Int: 32-bit signed integer
8. Long: a signed integer of 64 bits
9. Sbyte: signed 8-bit integer
10. Short: 16 bits signed
11. Uint: 32 bits unsigned
12. Ulong: unsigned 64 bits
13. Ushort: unsigned 16 bits
The exact size of a variable is dependent on the platform that is being used
which can be found out by using the Sizeof method. This expression is going
to yield the size of the storage that is being used for objects in terms of bytes.
Syntax
Using system;
Namespace dataclass application
{
Class program
{
Static void main (string [] args)
{
Console. Write line (size of int: {0}, Sizeof (int));
Console. ReadiLine ()
}
}
}
REFERENCE CLASS
You are not going to actually store any data in a variable with the reference
class. Basically, you are just going to be referring to a location on the
programs memory. When you use multiple variables, your reference class is
going to refer to the location for those classes. Should the data that is in that
location be modified by a variable, then another variable is going to
automatically reflect the change.
OBJECT CLASS
This class is going to be the base class for every data class that you find in
C#. The CTS (Common Class System) is going to use an alias when using the
system. Object class. This object class is going to have the option of being
assigned to values for other classes that are going to be discussed in this
chapter as long as the class is predefined by the program or defined by the
user. Before you have the option of assigning values, it is going to need to be
converted.
Whenever an object class is converted it is going to be known as boxing and
when it is converted to a value class it will be called unboxing.
DYNAMIC
Any value for any class can be stored in the dynamic class. You will need to
check these classes of variables as they take place at run time. A dynamic
class is going to be similar to the object class however the class check is
going to take place at compile time for the object class.
Syntax
Dynamic < variable_ name> = value;
STRING CLASS
This class will allow you to assign any value for a string to any variable. The
string class is going to contain an alias in the system string class. This class is
also derived from the object class. You will notice the value for the string
class is going to be assigned through the use of a string literal which comes in
two forms. Quoted and @quoted.
The user defined reference classes are known as interface, delegate and class.
POINTER CLASS
The pointer variables are going to be storing the memory addresses for other
classes. These pointers are going to have the same capabilities as the pointers
in other C languages.
Syntax
Class * identifier;
CHAPTER SEVEN
CLASS CONVERSION IN C#

C # class conversion is going to be the act of converting a data class to


another data class. You may also know these conversions as class
casting. You will discover that there are two different classes of casting.
1. Implicit conversion: the class converted under this is going to be
performed by C# in the same manner for the class that is being
converted. Take for example when convariations are going from
smallest to largest which will make your convariations derived class to
base class.
2. Explicit conversion: explicit conversions are going to be done by users
when they are working with predefined functions. These conversion
will require cast operators.
Syntax

using System;
namespace TypeClassConversionApplication
{
class ExplicitConversion
{
static void Main (string [] args)
{
double d = 5673.74;
int i;
// cast double to int.
i = (int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
}
CONVERSION METHODS
1. Toboolean: a Boolean class will be converted
2. To byte: bytes will be converted
3. Tochar: characters in a single Unicode character will be converted.
4. Todatetime: your date and time structure will be converted
5. Todecimal: a floating point or integer is going to be converted into a
decimal class.
6. Todouble: the class is going to be converted to a double class
7. Toint16: a class will be converted to a 16-bit integer
8. Toint32: a class will be converted to a 32-bit integer
9. Toin64: a class will be converted into a 64-bit integer
10. Tosbyte: your class will be converted into a signed byte class
11. Tosingle: a class will be converted to a floating-point number, but it
will be small.
12. To string: your class will be converted to a string
13. To class: your class will be converted to a class that you specify.
14. Touint16: you will have an unsigned int class
15. Touint32: you will have an unsigned long class
16. Touint64: you will get an unsigned big integer.
Example:

using System;
namespace ClassConversionApplication
{
class StringConversion
{
static void Main (string [] args)
{
int i = 75;
float f = 53.005f;
double d = 2345.7652;
bool b = true;
Console.WriteLine(i.ToString());
Console.WriteLine(f.ToString());
Console.WriteLine(d.ToString());
Console.WriteLine(b.ToString());
Console.ReadKey();
}
}
}
CHAPTER EIGHT
THE VARIABLES FOUND IN C#

V ariables are essentially nothing except a name that is going to be placed


in a storage area in which it is going to be manipulated. Each variable
is going to contain specific class where the size is going to be determined as
well as the layout for the memory of the variable. Each memory is going to
have a range of values that are going to be stored inside along with a set of
operations that you can apply to every variable.
Some of the basic value classes provided by C# are:
1. Integral class: char, ulong, long, uint, int, ushort, short, byte, sbyte
2. Floating point: double and float
3. Decimal class: decimal
4. Boolean: true, false, assigned
5. Nullable class: nullable
C# makes it to where you are able to define value class with variables such as
class and enum.
DEFINING VARIABLES
Syntax
<data_class> <variable_lists>;
The data class has to be part of the C# data class and has to be valid. Your
variable list has to consist of at least one identifier which will be separated by
a comma.
Variable definitions:

int i, j, k;
char c, ch;
float f, salary;
double d;

Initializing Variables
when initializing variables, there is going to be an equals sign which will be
followed by a constant expression.
Syntax
Variable_name = value;
You can initialize variables inside their declarations. This initializer is going
to have an equals sign followed by a constant expression
Syntax
<data_class> <variable_name> = value;
Example

int d = 3, f = 5; /* initializing d and f. */


byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */

You need to work on initializing variables the correct way or otherwise the
program is going to give you results that you are not expecting.
Example

using System;
namespace VariableDefinition
{
class Program
{
static void Main(string[] args)
{
short a;
int b ;
double c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console. WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}

Accepting values from the user


Your console class is going to be found in the system namespace which will
then give you a function known as readline() which you are going to use for
accepting the input that you get from your users and storing it as variables.
Example

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

your convert toint32 () function is going to take the data and convert it so that
it can be read by the program.
LVALUE AND RVALUE EXPRESSION
There are two different expressions that you will find in C#
1. Rvalue: this expression is going to appear at the right but not the left
side of your work.
2. Lvalue: this is going to appear to the left or right hand while working.
The variables for the lvalues are going to make it to where they show up on
the left side. The numeric literals are going to be the r values which explains
why they are unable to assign therefore cannot appear on the left side of their
brain.
CHAPTER NINE
C# CONSTANTS AND LITERALS

Y our constant is going to refer to a value that is fixed and cannot be


altered while the program is performing code. The values that are fixed
are going to be known as literals. A constant is going to be any data class
such as an integer or a character. You can also have enumeration constants as
well.
You are going to treat your constant like a regular variable except for the fact
that your values are not going to be able to be changed after they have been
defined.
INTEGER LITERALS
Integer literals are going to be things such as decimals or hexadecimals. The
prefix is going to tell you the base or radix. It is going to either be 0x or 0X
when you are working with hexadecimal, but there is not going to be a prefix
id for the decimals.
Your integer literals can also use U and L for the suffix for those that are
unsigned and long. The suffix will either be capitalized or lowercase
depending on the order.
Example

85 /* decimal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
FLOATING POINT LITERALS
The floating point literals will be composed of four parts: exponent,
fractional, integer, decimal. You are also going to be able to represent these
literals in the exponential form or their decimal form.
Example

3.14159 /* Legal */
314159E-5F /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */

When working with the decimal form you need to ensure that you include the
decimal point, the exponent, or even both. For the exponential form you will
need to include the integer part, the fractional part, or if you choose to, you
can do both. For signed exponents, you are going to use e or E.
CHARACTER CONSTANTS
The character literals are going to be surrounded by a set of single quotes and
are going to be stored in a char class. These literals are going to be plain
characters or even escape sequences, you may even see some that are
universal characters.
Some characters that are used in C# are going to be preceded by backslashes
which mean that they have a special meaning and are going to represented
differently.
Escape sequences are:
1. \xhh: hexadecimal with multiple digits
2. \\: \character
3. \v: vertical tab
4. \’: ‘character
5. \t: horizontal tab
6. \”: “ character
7. \r: carriage return
8. \?: ?character
9. \n: newline
10. \a: alerts
11. \f: form feed
12. \b: backspace
Example

using System;
namespace EscapeChar
{
class Program
{
static void Main(string[] args)
{
Console. WriteLine("Hello\tWorld\n\n");
Console.ReadLine();
}
}
}
STRING LITERALS
A string literal or constant is going to be surrounded by double quotes, or
contain an at symbol. These strings are going to be full of characters that are
going to look similar to the character literals.
Long lines can be broken up into multiple lines through the use of string
literals as long as whitespaces are used for the separation process.
Example

"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
@"hello dear"
DEFINING CONSTANTS
A constant is going to be defined by using the const keyword.
Syntax
Const <data_class> <constant_name> = value;
Example

using System;
namespace DeclaringConstants
{
class Program
{
static void Main(string[] args)
{
const double pi = 3.14159;
// constant declaration
double r;
Console. WriteLine("Enter Radius: ");
r = Convert.ToDouble(Console.ReadLine());
double areaCircle = pi * r * r;
Console. WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
Console.ReadLine();
}
}
}
CHAPTER TEN
C# OPERATORS

T he operators are going to be the symbols that inform the compiler what
action to perform in mathematical or logical expressions. There are
operators that are built into C# such as:
1. Misc
2. Arithmetic
3. Assignment
4. Relational
5. Bitwise
6. Logical
ARITHMETIC OPERATORS
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
5. Modulus (%)
6. Increases by one (++)
7. Decreases by one (- -)
RELATIONAL
1. Is the value true? (==)
2. Are the values equal (!=)
3. Greater than (>)
4. Less than (<)
5. Greater than or equal to (>=)
6. Less than or equal to (<=)
LOGICAL
1. Logical and (&&)
2. Logical or (||)
3. Logical not (!)
Bitwise
1. Binary and (&)
2. Binary or (|)
3. Binary XOR (^)
4. Binary ones (~)
5. Binary left shift (<<)
6. Binary right shift (>>)
ASSIGNMENT
1. Assigning values (=)
2. And assignment (+=)
3. Subtract and assign (- =)
4. Multiple and assign (*=)
5. Divide and assign (/=)
6. Modulus and assign (%=)
7. Left shift and assign (<<=)
8. Right shift and assign (>>=)
9. Bitwise and assign (&=)
10. Bitwise exclusive or and assign (^=)
11. Bitwise inclusive or and assign (!=)
MISC
1. Sizeof()
2. Classof()
3. Variable address (&)
4. Pointer to variables (*)
5. Conditional expression (? : )
6. Object class determination (is)
7. Does not rise expectation if cast falls (as)
OPERATOR PRECEDENCE
The precedence in C# is going to tell you what group of terms is going to be
evaluated first. There are certain operators that have a higher precedence than
others such as multiplication is going to be higher than addition.
Here at the precedence for C#
1. Postfix: (), [], ., ++, --
2. Unary:+, -, !~, ++, --, (class)*, &, Sizeof
3. Multiplicative: *, /, %
4. Additive: +, -
5. Shift: << , >>
6. Relational: <, <=, >, >=
7. Equality: ==, !=
8. Bitwise and: &
9. Bitwise XOR: ^
10. Bitwise or: |
11. Logical and: &&
12. Logical or: ||
13. Conditional: ?:
14. Assignment: =, +=, -=, ^=, /=, %=, =>, >=, <<=, &=, ^=, |=
15. Comma: ,
CHAPTER ELEVEN
DECISION MAKING WITH C#

Y ou are going to use decision making in C# to learn how a program is


working. The structure of the decision is going to mean that you need
to tell the program which condition needs to be evaluated and tested as well
as any statements that need to be carried out in the event that the condition is
true or false.
DECISION-MAKING STATEMENTS
1. If statement: there is going to be a boolean expression
2. If-else statement: this is an if statement which will be followed by an
else statement.
3. Nested statement: one statement stuck inside of another statement.
4. Switch statement: this statement will enable the variables to be tested
for equality.
5. Nested switch statements: one switch statement placed inside of
another.
? : operator
This operator is going to be able to be used in place of an if-else statement.
Syntax
Expression one ? expression two : expression three ;
The value of this expression is going to be determined by how expression one
is evaluated and if it is found to be true. Then expression two will be
evaluated and become the value for the question mark. However, if
expression one is found to be false, then expression three will become
evaluated and become the value for your expression.
CHAPTER TWELVE
LOOPS

I n some situations, you are going to discover that you need to carry out a
particular block of code multiple times in a row. The statements that are
going to be performed in order that they are written.
Most programming languages are going to give you control structures that are
going to enable you to work with execution paths that are more complicated.
Loops are going to allow for statements to be performed multiple times in a
row without having to constantly class the statement out that needs to be
performed.
1. While loop: this is going to repeat the chosen statements if a condition
is true.
2. For loop: the statements will be carried out and abbreviated so that the
loop variable can be managed.
3. Do while loop: the condition is going to be tested at the end of the body
for the loop.
4. Nested loop: just like other nested statements, this is going to be one
loop inside of another.
LOOP CONTROL STATEMENTS
Control statements are going to change the way that a loop is performed from
how it normally would be. Whenever the execution leaves the scope, any
automatic object is going to be destroyed.
1. Break statement: the loop or switch statement will be terminated while
the statement that follows the loop or switch is carried out.
2. Continue statement: the loop will skip all of its body and test the
condition before it reiterates.
INFINITE LOOP
Loops are going to fall into this category when their condition is never found
to be false. For loops are usually the ones that are going to fall into this
category. Due to the fact that none of the three expressions are going to be
required, you can cause an endless loop to occur by leaving the condition
expression empty.
Example

using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
for (; ; )
{
Console. WriteLine("Hey! I am Trapped");
}
}
}
}

Whenever the conditional expression is not there, it is going to be assumed to


be true. You may find that you have to initialize the increment expression.
However, many programmers use for ( ; ; ) to construct an infinite loop.
CHAPTER THIRTEEN
ENCAPSULATION IN C#

Y ou will define encapsulation as the process of enclosing a single item or


more inside of a logical or physical package. Encapsulation is done
inside of programming languages that are object-oriented, and methodology
ends up preventing the access to implementation details.
Abstraction and encapsulation are going to be features that you can only find
in object oriented programming. Abstraction, however, turns relevant
information in the code into a visible piece of the code while encapsulation
allows the programmer to implement the level of abstraction that they want in
their code.
There are access specifiers that are going to cause encapsulation to be
implemented. Access specifiers are going to define the scope and how visible
a class member is. These are the specifiers that C# supports.
1. Protected internal
2. Open
3. Internal
4. Private
5. Protected
OPEN
These specifiers are going to enable the class to show the member variables
and functions so that other objects and functions can see them. When a
member is Open, it can be accessed from the outside.
Example

using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
Open double length;
Open double width;
Open double GetArea()
{
return length * width;
}
Open void Display()
{
Console. WriteLine("Length: {0}", length);
Console. WriteLine("Width: {0}", width);
Console. WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class PerformRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}

In this example, you can see that the member variable length and width are
going to be Open so that they can be accessed from your function through the
use of the class name. Your member functions are only going to have the
ability to access the variables directly without using any of the class
instances. They are also going to be declared as Open by using the main()
function.
PRIVATE
Private specifiers are going to enable a class to hide the member variables
and functions from other things in the code. The only functions that you find
in the same class are going to have the ability to access the private members.
There are even going to be instances where classes are not going to be able to
access private members.
Example

using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
private double length;
private double width;
Open void Acceptdetails()
{
Console. WriteLine("Enter Length: ");
length = Convert.ToDouble(Console.ReadLine());
Console. WriteLine("Enter Width: ");
width = Convert.ToDouble(Console.ReadLine());
}
Open double GetArea()
{
return length * width;
}
Open void Display()
{
Console. WriteLine("Length: {0}", length);
Console. WriteLine("Width: {0}", width);
Console. WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class PerformRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}

In the example above the member, variables are going to be declared private
so that the function cannot access them. The member functions are going to
show the variables, however. Due to the fact, that the member functions are
open, they can be accessed from the main functions by using the instance of
the class name.
PROTECTED ACCESS SPECIFIER
This specifier is going to allow for the child class to have access to the
member variables and functions in its base class. This is going to be helpful
when you are working with inheritance.
INTERNAL ACCESS SPECIFIER
The internal access specifier is going to allow the member functions and
variables to be exposed to other functions and objects that are in the assembly
that you are working with. Therefore, you are going to be able to have access
to any class or method as long as it is defined in the application where the
member has been defined.
Example

using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
internal double length;
internal double width;
double GetArea()
{
return length * width;
}
Open void Display()
{
Console. WriteLine("Length: {0}", length);
Console. WriteLine("Width: {0}", width);
Console. WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class PerformRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}

This example shows that the member function is not declared with the
specifier that offers access. Therefore, the default access specifier for the
class member is not mentioned due to the fact that it is private.
PROTECTED INTERNAL ACCESS SPECIFIER
This specifier is going to take a class and hide the member variables and
functions from other class objects and functions except for the child cases
that are in the same application. You are going to use this method when you
are implementing inheritance.
CHAPTER FOURTEEN
METHODS THAT ARE USED IN C#

T
main.
he method is the group of statements that work in order to perform a
task. Each program in C# is going to have one class method named

In order to use a method you have to


1. Define your method
2. Call your method
DEFINING METHODS
Whenever a method is defined, you have to declare the elements of the
structure.
Syntax
<access specifier> <return class> <method name> (parameter list)
{
Method body
}
Some of the elements of the method are:
1. Access specifier: the visibility of the variable will be determined by
another class.
2. Return class: the method is going to return a value. This returned class
is going to be the data class of the value that is returned to you. Should
the method not return a value then the return class is going to be void.
3. Method name: the method name is the identifier that is going to be case
sensitive. It is not going to be the same as other identifiers that are
declared in the class.
4. Parameter list: between the parentheses the parameters are going to be
used to pass and obtain data from the method that is being used.
Parameters are going to refer to the order, number, and class of
parameters that a method is using. Parameters do not have to be used.
5. Method body: your instructions are going to be here which you are
going to need in order to complete the steps that need to be carried out.
Example

class NumberManipulator
{
Open int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
...
}
CALLING METHODS
A method is going to be called by using the name of the method that you
want to call.
Example

using System;
namespace CalculatorApplication
{
class NumberManipulator
{
Open int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();
//calling the FindMax method
ret = n.FindMax(a, b);
Console. WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
}

You also have the option of calling Open methods from other classes that are
going to be used in the instances for that class.
Example

using System;
namespace CalculatorApplication
{
class NumberManipulator
{
Open int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
if(num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
class Test
{
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();
//calling the FindMax method
ret = n.FindMax(a, b);
Console. WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
}
RECURSIVE METHOD CALL
This method is a call in and of itself. It is known as recursion.
Example

using System;
namespace CalculatorApplication
{
class NumberManipulator
{
Open int factorial(int num)
{
/* local variable declaration */
int result;
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num;
return result;
}
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
//calling the factorial method
Console. WriteLine("Factorial of 6 is : {0}", n.factorial(6));
Console. WriteLine("Factorial of 7 is : {0}", n.factorial(7));
Console. WriteLine("Factorial of 8 is : {0}", n.factorial(8));
Console.ReadLine();
}
}
}
PASSING PARAMETERS TO METHODS
Whenever a parameter is called, you have to pass the parameter into the
method. There are at least three ways that you are going to be able to pass the
method.
1. Value parameter: the value parameter is going to copy the value of the
argument into the formal parameter of the function. When this is done,
any changes that are made to the parameter are not going to affect the
argument.
2. Reference parameter: your reference is going to be copied over to the
memory location for your argument into the formal parameter. This
ultimately means that the changes you make to the parameters are going
to affect your argument.
3. Output parameters: you will get more than one value returned.
CHAPTER FIFTEEN
NULLABLES FOUND IN C#

N ullable classes are a special class of data that is going to assign a


normal range into null values.
You can store any value from -2,147,483, 648 all the way up to 2, 147,483,
647 or null. You can also assign values that have a true, false, or null output.
Syntax
< data_class> ? <variable_name> = null;
Example

using System;
namespace CalculatorApplication
{
class NullablesAtShow
{
static void Main(string[] args)
{
int? num1 = null;
int? num2 = 45;
double? num3 = new double?();
double? num4 = 3.14157;
bool? boolval = new bool?();
// display the values
Console. WriteLine("Nullables at Show: {0}, {1}, {2}, {3}", num1, num2,
num3, num4);
Console. WriteLine("A Nullable boolean value: {0}", boolval);
Console.ReadLine();
}
}
}
NULL COALESCING OPERATOR ( ? ? )
The coalescing operator is used whenever the nullable value class and
reference classes are used. You will use the coalescing operator for
convariation of an operand to the class of another nullable value class
operand in which convariation is possible.
Should the value of your first operand be null, so, when the operator returns
the value from your second operand, it is going to be returning the value for
the first operand.
Example

using System;
namespace CalculatorApplication
{
class NullablesAtShow
{
static void Main(string[] args)
{
double? num1 = null;
double? num2 = 3.14157;
double num3;
num3 = num1 ?? 5.34;
Console. WriteLine(" Value of num3: {0}", num3);
num3 = num2 ?? 5.34;
Console. WriteLine(" Value of num3: {0}", num3);
Console.ReadLine();
}
}
}
CHAPTER SIXTEEN
ARRAYS FOUND IN C#

A rrays are going to be storing fixed sized sequential collections of object


or data classes. Arrays can be used in order to store a collection of data
that is going to be more useful as an array rather than as a different data class.
It also makes it to where it is stored at contiguous memory locations.
Rather than declaring the individual variables, you are going to be able to
declare one variable in the array as a number and use square brackets in order
to represent the individual variable. Your variables are going to have a place
on an index which is going to be used when trying to access that element.
Arrays are going to consist of contiguous memory locations where the lowest
address is going to correspond to the first element.
Declaring arrays
SYNTAX
Dataclass [] array name;
1. Data class is going to tell you what class of elements is in your array
2. The square brackets are going to tell you the rank of the array. The rank
will tell you the size of the array.
3. Array name is obviously going to tell you the name of your array you
are working with.
Example
Double [ ] hello ;
INITIALIZING ARRAYS
When an array is declared you are not going to be initializing the array in the
memory of the program. Whenever the array variables are initialized, then
you can assign values to that array.
Arrays are known as reference class which means you need to use the new
keyword in order to create the instance that is going to take place in your
array.
Example:
Double [ ] hello = new double [ 39 ]
ASSIGNING VALUES TO ARRAYS
Values can be assigned to individual array elements through the use of the
index number. You can also assign the values that you need to assign to the
array at the time of declaration. There is also the option of creating and
initializing an array manually.
Another way you can assign values to arrays is to omit the size of the array.
Or, you can copy the variables in your array into another target array
variable. When you do this, both the target and the source point are going to
be located in the same location for the memory.
Whenever an array is created, the C# compiler is going to initialize every
element of the array to a value that is set as the default value based on the
class of array you are working with.
ACCESSING ARRAY ELEMENTS
Elements are going to be accessed through the index. You will do this by
placing the index for that element inside of a set of square brackets after the
name of your array.
Example:

using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100;
}
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
Console. WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
}
}
}
FOR EACH LOOP
For each statement is going to be used in iterating through arrays.
Example

using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n is an array of 10 integers */
/* initialize elements of array n */
for ( int i = 0; i < 10; i++ )
{
n[i] = i + 100;
}
/* output each array element's value */
foreach (int j in n )
{
int i = j-100;
Console. WriteLine("Element[{0}] = {1}", i, j);
}
Console.ReadKey();
}
}
}
ARRAYS
1. Multidimensional array
2. Jagged array
3. Passing array to functions
4. Param array
5. The array class
CHAPTER SEVENTEEN
STRINGS IN C#

W ith C# you can use strings as arrays. But, one of the more common
things to do is to use a string keyword in order to declare the string
variable. String keywords are an alias for the system. String.
CREATING STRING OBJECTS
String objects can be created by:
1. Call a formatting method in order to convert a value or object to the
string representation
2. Assigning a string literal to the string variable retrieving property or
calling a method that is going to return a string
3. String class constructor
4. Using a string concatenation operator.
Example

using System;
namespace StringApplication
{
class Program
{
static void Main(string[] args)
{
//from string literal and string concatenation
string fname, lname;
fname = "Rowan";
lname = "Atkinson";
string fullname = fname + lname;
Console. WriteLine("Full Name: {0}", fullname);
//by using string constructor
char[] letters = { 'H', 'e', 'l', 'l','o' };
string greetings = new string(letters);
Console. WriteLine("Greetings: {0}", greetings);
//methods returning string
string[] sarray = { "Hello", "From", "Tutorials", "Point" };
string message = String.Join(" ", sarray);
Console. WriteLine("Message: {0}", message);
//formatting method to convert a value
DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
string chat = String.Format("Message sent at {0:t} on {0:D}", waiting);
Console. WriteLine("Message: {0}", chat);
}
}
}
PROPERTIES OF THE STRING CLASS
1. Chars: the char object will be obtained at a particular position in the
string object
2. Length: the number of characters in your string object
METHODS FOR A STRING CLASS
String classes have many methods that are going to assist in making your
work with string objects easier.
1. Open static int compare (string strA, string strB)
2. Open static int compare (string strA, string strB, bool ignoreCase )
3. Open static string concat (string str0, string str 1)
4. Open static string concat( string str0, string str1, string str 2)
5. Open static string concat (string str0,string str1, string str2, string str 3)
6. Open bool contains (string value)
7. Open static string copy (string str)
8. Open void copyto (int sourceindex, char [] destination, int
destinationindex, int count)
9. Open bool endswith (string value)
10. Open bool equals (string value)
11. Open static bool equals (string a, string b)
12. Open static string format (string format, object arg 0)
13. Open int index of (char value)
14. Open int index of (string value)
15. Open int indexof (char value, int startindex)
16. Open int indexof (string value, int start index)
17. Open int indexof any (char [] anyof)
18. Open int index of any (char [] anyof, int start index)
19. Open string insert (int startindex, string value)
20. Open static bool is null or empty (string value)
21. Open static string join (string separator, params string [] value)
22. Open static string join (string, string [] value, int start index, int count)
23. Open int last index of (char value)
24. Open int last index of (string value)
25. Open string remove (int start index)
26. Open string remove (int start index, int count)
27. Open string replace (char old char, cha new char)
28. Open string replace (string old value, string new value)
29. Open string [] split (params char [] separator)
30. Open string [] split (char [] separator, int count)
31. Open bool starts with (string value)
32. Open char [] to char array ()
33. Open char [] to char array (int start index, int length)
34. Open string to lower ()
35. Open string to upper ()
36. Open string trim ()
Example

using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str1 = "This is test";
string str2 = "This is text";
if (String.Compare(str1, str2) == 0)
{
Console. WriteLine(str1 + " and " + str2 + " are equal.");
}
else
{
Console. WriteLine(str1 + " and " + str2 + " are not equal.");
}
Console.ReadKey() ;
}
}
}

String contains string example

using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str = "This is test";
if (str.Contains("test"))
{
Console. WriteLine("The sequence 'test' was found.");
}
Console.ReadKey() ;
}
}
}

Obtaining substrings example

using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str = "Last night I dreamt of San Pedro";
Console. WriteLine(str);
string substr = str.Substring(23);
Console. WriteLine(substr);
}
}
}

Joining strings together example

using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string[] starray = new string[]{"Down the way nights are dark",
"And the sun shines daily on the mountain top",
"I took a trip on a sailing ship",
"And when I reached Jamaica",
"I made a stop"};
string str = String.Join("\n", starray);
Console. WriteLine(str);
}
}
}
CHAPTER EIGHTEEN
C# STRUCTURES

W ith C# there are value classes for the data classes that are going to
help you make single variables that will hold any data that is related
to that data class. The struct keyword is what you are going to use in order to
create a structure.
A structure is going to be used in representing records.
DEFINING STRUCTURES
In order to define a structure, you are going to use a struct statement. This
statement is going to be used in defining a new data class that has more than
one member inside of your program.
Example

using System;
struct Books
{
Open string title;
Open string author;
Open string subject;
Open int book_id;
};
Open class testStructure
{
Open static void Main(string[] args)
{
Books Book1; /* Declare Book1 of class Book */
Books Book2; /* Declare Book2 of class Book */
/* book 1 specification */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;
/* book 2 specification */
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Book2.subject = "Telecom Billing Tutorial";
Book2.book_id = 6495700;
/* print Book1 info */
Console. WriteLine( "Book 1 title : {0}", Book1.title);
Console. WriteLine("Book 1 author : {0}", Book1.author);
Console. WriteLine("Book 1 subject : {0}", Book1.subject);
Console. WriteLine("Book 1 book_id :{0}", Book1.book_id);
/* print Book2 info */
Console. WriteLine("Book 2 title : {0}", Book2.title);
Console. WriteLine("Book 2 author : {0}", Book2.author);
Console. WriteLine("Book 2 subject : {0}", Book2.subject);
Console. WriteLine("Book 2 book_id : {0}", Book2.book_id);
Console.ReadKey();
}
}
FEATURES OF A C# STRUCTURE
Since you already have the structure that was created in the example above,
you are going to realize that they are different than structures that you find in
other C programming languages. C# includes these features for their
structures.
1. Structures are allowed to have methods, fields, properties, events,
operator methods, and indexers.
2. These structures are allowed to have constructors but cannot have
destructors.
3. Inheritance is forbidden.
4. You cannot use a base for any other structure or class
5. The structure is going to implement at least one interface
6. The structure members are not allowed to be specified as protected,
virtual, or abstract.
7. Whenever a struct object is created with the new operator, you are
going to be creating the object and the constructor that is going to go
with it.
8. Should the new operator not be used, then the field is going to be
unassigned until the fields are initialized.
CLASS VS. STRUCTURE
There are at least three differences between a structure and a class that is
going to be used in C#
1. Structures are not allowed to have default constructors
2. The classes are going to use reference classes while structs use value
classes
3. A structure cannot use inheritance
Example

using System;
struct Books
{
private string title;
private string author;
private string subject;
private int book_id;
Open void getValues(string t, string a, string s, int id)
{
title = t;
author = a;
subject = s;
book_id = id;
}
Open void display()
{
Console. WriteLine("Title : {0}", title);
Console. WriteLine("Author : {0}", author);
Console. WriteLine("Subject : {0}", subject);
Console. WriteLine("Book_id :{0}", book_id);
}
};
Open class testStructure
{
Open static void Main(string[] args)
{
Books Book1 = new Books(); /* Declare Book1 of class Book */
Books Book2 = new Books(); /* Declare Book2 of class Book */
/* book 1 specification */
Book1.getValues("C Programming",
"Nuha Ali", "C Programming Tutorial",6495407);
/* book 2 specification */
Book2.getValues("Telecom Billing",
"Zara Ali", "Telecom Billing Tutorial", 6495700);
/* print Book1 info */
Book1.display();
/* print Book2 info */
Book2.display();
Console.ReadKey();
}
}
CHAPTER NINETEEN
ENUMS IN C#

E numerations are for sets of integer constants that are named. These
enumerated classes are going to be declared by use of the enum
keyword.
A C# enumeration is for the value data value class. In the end, the
enumeration is going to hold on to its own values and is not going to inherit
or pass inheritance.
DECLARING ENUM VARIABLE
Syntax
Enum <enum_name>
{
Enumeration list
};
1. The enum_name will be the class of enumeration being used
2. The enumeration list is going to be a list of identifiers that are separated
by commas
Every symbol in the list of enumeration is going to stand for a particular
integer. The greater than value is going to precede any other symbol. By
default, your first enumeration symbol will be 0.
Example enum num { 1, 2, 3, 4, 5, 6} ;
Example of enum variables

using System;
namespace EnumApplication
{
class EnumProgram
{
enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
static void Main(string[] args)
{
int WeekdayStart = (int)Days.Mon;
int WeekdayEnd = (int)Days.Fri;
Console. WriteLine("Monday: {0}", WeekdayStart);
Console. WriteLine("Friday: {0}", WeekdayEnd);
Console.ReadKey();
}
}
}
CHAPTER TWENTY
CLASSES YOU FIND IN C#

W hen a class is defined, you are going to be defining a blueprint for that
data class. You are not going to actually define any data, but it is
going to define what the name of the class means. This means that it is going
to contain the object in the class as well as what the operations are going to
do. The methods and variables in your class are going to be known as the
members of the class.
DEFINING A CLASS
Class definitions are going to start with the keyword of class and will be
followed by the name of the class. Your class body is going to be enclosed by
a pair of curly braces.
Example

<access specifier> class class_name


{
// member variables
<access specifier> <data class> variable1;
<access specifier> <data class> variable2;
...
<access specifier> <data class> variableN;
// member methods
<access specifier> <return class> method1(parameter_list)
{
// method body
}
<access specifier> <return class> method2(parameter_list)
{
// method body
}
...
<access specifier> <return class> methodN(parameter_list)
{
// method body
}
}

Keep in mind:
1. In order to access your specifiers by a particular access rule, you are
going to have access to the members and the class. If you do not
mention anything, then the default is going to be used which is the
internal class. Default for the member is going to be private.
2. A data class needs to be specified by the class of variable that you are
using as well as the return class so that the data class method is returned
as you want it if you are using one.
3. In order to access a class member, you need to use the dot operator
4. Dot operator links are going to tell you the name of the object and the
name of the member.
Example

using System;
namespace BoxApplication
{
class Box
{
Open double length; // Length of a box
Open double breadth; // Breadth of a box
Open double height; // Height of a box
}
class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of class Box
Box Box2 = new Box(); // Declare Box2 of class Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
Console. WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
Console. WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}
MEMBER FUNCTIONS AND ENCAPSULATION
The member functions are part of a class with its own definition and
protoclass inside the class definition which will be similar to other variables.
These functions operate the objects of a class where the member can access
all the members of the class of that object.
The member variables are known as attributes that will be kept private for
implementing encapsulation. It is these variables that will have access to the
Open functions.
Example

using System;
namespace BoxApplication
{
class Box
{s
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
Open void setLength( double len )
{
length = len;
}
Open void setBreadth( double bre )
{
breadth = bre;
}
Open void setHeight( double hei )
{
height = hei;
}
Open double getVolume()
{
return length * breadth * height;
}
}
class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of class Box
Box Box2 = new Box();
double volume;
// Declare Box2 of class Box
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console. WriteLine("Volume of Box1 : {0}" ,volume);
// volume of box 2
volume = Box2.getVolume();
Console. WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}
CONSTRUCTORS
The constructors for a class are going to be special functions for a class that
will perform as needed when you create new objects in that class.
Constructors will have the same name as the name of the class, but you will
not get a return class.
Example

using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
Open Line()
{
Console. WriteLine("Object is being created");
}
Open void setLength( double len )
{
length = len;
}
Open double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line();
// set line length
line.setLength(6.0);
Console. WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
}

The default constructor will not give you any parameter, however, if you
need a constructor can have a parameter. There are some parameters known
as parameterized constructors that are going to assist in assigning the primary
value for an object when it is created.
Example

using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
Open Line(double len) //Parameterized constructor
{
Console. WriteLine("Object is being created, length = {0}", len);
length = len;
}
Open void setLength( double len )
{
length = len;
}
Open double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line(10.0);
Console. WriteLine("Length of line : {0}", line.getLength());
// set line length
line.setLength(6.0);
Console. WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
}
DECONSTRUCTOR
The deconstructor is also a special function that is going to be carried out
when there is a class that falls out of its scope. The deconstructor is going to
have the same name as the class but will have a tilde before it and is not
going to be able to have any parameters or return values.
Deconstructors are going to be useful when you need to release the memory
before you leave a program, but the deconstructor is not going to be able to
be inherited or overload.
Example

using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
Open Line() // constructor
{
Console. WriteLine("Object is being created");
}
~Line() //destructor
{
Console. WriteLine("Object is being deleted");
}
Open void setLength( double len )
{
length = len;
}
Open double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line();
// set line length
line.setLength(6.0);
Console. WriteLine("Length of line : {0}", line.getLength());
}
}
}
CONCLUSION

T hank you for making it through to the end of C#, let’s hope it was
informative and able to provide you with all of the tools you need to
achieve your goals whatever it may be.
The next step is to use the new programming language that you have learned
and put it to go use. No matter what it is that you are using C# for, you are
going to discover that there are going to be similarities between every C
language.
Make sure that you are patient when learning a programming language
because if you are not then you are going to be causing yourself to have to go
back and correct a lot of mistakes which is going to take up valuable time that
you could be using for something else.
Thank you and good luck.

You might also like