C - Become A Master in C (C Programming Language, C - Dorsey, Richard
C - Become A Master in C (C Programming Language, C - Dorsey, Richard
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
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
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
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#
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
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();
}
}
}
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
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#
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");
}
}
}
}
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
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#
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#
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() ;
}
}
}
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() ;
}
}
}
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);
}
}
}
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
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.