Cpe 317 Visual Programming
Cpe 317 Visual Programming
CONTENTS
Aim Of Lesson
To create visual application, Using and managin windows forms and components, To be able to
progammed methods,classes,objects nad functions in programing langugae. Using and managing
database.
Books, Videos and Online Course Documents
1. https://dotnet.microsoft.com/learn/csharp
2. https://docs.microsoft.com/en-us/visualstudio/get-started/csharp/visual-studio-ide?view=vs-
2019
3. C# ile Görsel Programlama, Mücahit Furkan ARDOĞAN
4. https://gelecegiyazanlar.turkcell.com.tr/konu/c-sharp/egitim/c-101/c-dilinin-tarihcesi
5. Computer and Information Technology, Programming in Visual C# 2008,
Bradley−Millspaugh (https://epdf.pub/programming-in-visual-c-2008.html )
Evaluations
1 mid-term, 1 final exam and project
CHAPTER 1
As a verb, to program a computer is the writing of statements or commands that instruct the
computer how to process data. There are several programming languages used to program a
computer.
The platform and language on which the program will be written is selected. Codes are created
according to the characteristics of the programming language and translated into the machine
language that the computer can understand. As a result, Programming is a way to “instruct
the computer to perform various tasks” [2].
Visual Programming
Types of programming:
1. Non-Structed Programming
2. Structed Programming
3. Visual Programming
4. Object Oriented Programming
Programs can be developed as text in a text editor (Edit, Notepad, Wordpad, Vim etc.).
However, programs made with the use of visual elements become more understandable [3]. A
Visual Programming Language (VPL) is a programming language that uses graphical
elements and figures to develop a program using IDE (Integrated Development Environment.
A VPL employs techniques to design a software program in two or more dimensions, and
includes graphical elements, text, symbols and icons within its programming context. A visual
language can be one of a few types, such as icon-based languages, diagramming languages
and form-based language [4].
C# language was created by Anders Hejlsberg at Microsoft. It was developed around 2000 by
Microsoft as part of its .NET initiative and later approved as an international standard by Ecma (is a
standards organization for information and communication systems) in 2002 and ISO in 2003. C# is
one of the programming languages designed for the Common Language Infrastructure (CLI is is an
open specification (technical standard) developed by Microsoft and standardized by ISO and Ecma).
C# has its roots in the C family of languages and will be immediately familiar to C, C++, Java, and
JavaScript programmers. C# is a simple, modern, flexible, object-oriented, safe, and open source
programming language. The first version is C# 1.0 and The most recent version is 8.0, which was
released in 2019 alongside Visual Studio 2019. The creation of the C # name is as follows 😊
[5]
It’s used for a wide range of reasons but its popularity lies in its use for the following tasks [6].
It was designed with simplicity and ease of use as a priority, and because it’s a high level language it
reads closer to English. As a language, C# abstracts the complex details of the computer so you as the
developer can focus on programming instead of worrying about the little details. You can make
anything in C#, from web services to mobile apps, server applications and more [7].
Figure 1: C# applications.
C# is modern and easy to learn
C# is an object–oriented language
C# is easy to learn.
C# is safe
C# is versatile
C# is fast, open source, and cross platform
C# is evolving
C# supports native mobile apps
C# is friends with JavaScript
C# supports web browsers
Amazing tooling support
Strong community support [8]
The programming languages in Visual Studio run in the .NET Framework. The Framework provides
for easier development of Web-based and Windows-based applications, allows objects from different
languages to operate together, and standardizes how the languages refer to data and objects.
The .NET languages all compile to (are translated to) a common machine language, called Microsoft
Intermediate Language (MSIL). The MSIL code, called managed code, runs in the Common
Language Runtime (CLR), which is part of the .NET Framework [9].
The CLR does not know what language code it is running. All languages are translated into IL
(Common language) code. The common code generated by the compiler is then translated by the CLR
into native CPU machine commands. The C # command compiler is Csc.Exe.
When the C# program is executed, the assembly is loaded into the CLR, which might take various
actions based on the information in the manifest. Then, if the security requirements are met, the CLR
performs Just-In-Time (JIT) compilation to convert the IL code to native machine instructions. The
CLR also provides other services related to automatic garbage collection, exception handling, and
resource management. Code that's executed by the CLR is sometimes referred to as "managed code",
in contrast to "unmanaged code", which is compiled into native machine language that targets a
specific system. The following diagram illustrates the compile-time and run-time relationships of C#
source code files, the .NET Framework class libraries, assemblies, and the CLR.
Figure 3: Working steps of the C# project [11]
CHAPTER 2
If .Net Framework and Csc.Exe program (to convert C # codes to MSIL code) are available on your
computer, the C # program codes can be written in the text editör (ex. NotePad). However, since it will
be difficult to develop applications with the text editor, we need integrated development
environment (IDE). These environments provide facilities such as facilitating software development
and ensuring the security of the project.
Visual Studio integrated development environment is a creative launching package that you can use
to edit, debug, and build code, and then publish an applications. An integrated development
environment (IDE) is a feature-rich program that can be used for many aspects of software
development. Visual Studio includes compilers, code completion tools, graphical designers, and many
more features to ease the software development process.
To get started, download Microsoft Visual Studio 2019 and install it on your system using
link: https://visualstudio.microsoft.com/downloads/
There are three editions of Visual Studio 2019: Community, Professional, and Enterprise. We
will select Professional Edition. You can download it for free.
Finally the overview is selected and Visual Studio is launched as shown Figure 6.
A new project creation screen will appear as shown Figure 7. So the Visual Studio
environment is ready 😊.
C# use objects, which have properties, methods, and events. Each object is based on a class.
Object: Think of an object as a thing or a noun. Examples of objects are forms and controls.
Forms are the windows and dialog boxes you place on the screen; controls are the components
you place inside a form, such as text boxes, buttons, and list boxes.
Properties: Properties tell something about or control the behavior of an object such as its
name, color, size or location. You can think of properties as adjectives that describe objects.
When you refer to a property, you first name the object, add a period, and then name the
property.
Methods: Actions associated with objects are called methods. Methods are the verbs of
object-oriented programming. Some typical methods are Close, Show and Clear.
Events: You can write methods that execute when a particular event occurs. An event occurs
when the user takes an action such as clicking a button, pressing a key, scrolling, or closing a
window. Events also can be triggered by actions of other objects, such as repainting a form or
a timer reaching a preset point.
Classes: A class is a template used to create a new object. Classes contain the definition of all
available properties, methods, and events. Each time that you create a new object, it must be
based on a class.
For example, you may decide to place three buttons on your form. Each button is based on the Button
class and is considered one object, called an instance of the class. Each button (or instance) has its own
set of properties, methods, and events. One button may be labeled “OK”, one “Cancel”, and one
“Exit”. When the user clicks the OK button, that button’s Click event occurs; if the user clicks on the
Exit button, that button’s Click event occurs [9].
Console application takes inputs and displays output at a command-line console with access to three
basic streams: standard input, standard output, and standard error. Console applications don't have any
graphical user interface, they will have character-based interfaces [13].
Windows Form application is a Graphical User Interface (GUI) class library which is bundled
in .Net Framework. Its main purpose is to provide an easier interface to develop the applications for
desktop, tablet, PCs. Forms applications can contain the different type of controls like labels, list
boxes, buttons etc [14].
When C# programs are compiled, they are physically packaged into assemblies. Assemblies typically
have the file extension .exe or .dll, depending on whether they implement applications or libraries.
The simple Console application and Form application codes are shown in below Table 2. Let's
examine some of the codes in the Table 2.
Using directive: The using directive can appear at the beginning of a source code file, before
any namespace or type definitions. The using directive has three uses:
1. To allow the use of types in a namespace so that you do not have to qualify the use of
a type in that namespace:
using System.Text;
2. To allow you to access static members and nested types of a type without having to
qualify the access with the type name.
using static System.Console;
Ex: If we write the console application program by adding the code " using static
System.Console ", print line to screen line will change as “WriteLine("Hello World!")”.
3. To create an alias for a namespace or a type. This is called a using alias directive.
After that, “PC.MyCompany.Project” will be called “Project” in the application.
using Project = PC.MyCompany.Project;
namespace directive: Namespaces are not mandatory in a C# program. But, they do play an
important role in writing cleaner codes and managing larger projects. A namespace can have
following types as its members: Namespaces (Nested Namespace), Classes, Interfaces,
Structures, Delegates [16].
Namespaces help us to organize different members by putting related members in the same
namespace. Namespace also solves the problem of naming conflict. Two or more classes
when put into different namespaces can have same name.
1. We can define a namespace in C# using the namespace keyword as:
namespace Namespace-Name
{
//Body of namespace
}
Ex: A namespace MyNamespace is created. It consists of a class MyClass as its
member. MyMethod is a method of class MyClass.
namespace MyNamespace
{
class MyClass
{
public void MyMethod()
{
System.Console.WriteLine("Creating my namespace");
}
}}
The members of a namespace can be accessed using the dot(.) operator. The syntax for
accessing the member of namespace is,
Namespace-Name.Member-Name
Ex: If we need to create an object of MyClass, it can be done as,
MyNamespace.MyClass myClass = new MyNamespace.MyClass();
2. A namespace can be included in a program using the using keyword. The syntax is,
using Namespace-Name;
Ex:
using System;
The advantage of this approach is we don't have to specify the fully qualified name of
the members of that namespace every time we are accessing it.
Once the line “using System;” is included at the top of the program. We can write
Console.WriteLine("Hello World!"); Instead of the fully qualified name i.e.
System.Console.WriteLine("Hello World!");
namespace MyNamespace
{
namespace NestedNamespace
{
// Body of nested namespace
}
}
The entry point may optionally have one formal parameter. The parameter may have
any name, but the type of the parameter must be string[]. If the formal parameter is
present, the execution environment creates and passes a string[] argument containing
the command-line arguments that were specified when the application was
started. The string[] argument is never null, but it may have a length of zero if no
command-line arguments were specified.
CHAPTER 3
using System;
class Hello
{
static void Main()
{
Console.WriteLine("Hello, World");
Console.ReadKey();// Bir tuşa basana kadar çıktı ekranda kalır.
}
}
C# source files typically have the file extension .cs. Assuming that the “Hello, World”
program is stored in the file hello.cs, the program can be compiled with the Microsoft C#
compiler (Developer Command Prompt for VS 2019) using the command line.
which produces an executable assembly named hello.exe. The output produced by this
application when hello.exe is run:
3.1.2 Running using VS IDE
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
1. Start Visual Studio 2019. You'll see the following image on Windows. Select Create a
new project in the lower right corner of the image. [17]:
2. Visual Studio displays the New Project dialog: Before, Language, operation system and
application type are selected. After that, Choose the Console App (.NET Core) template,
and then choose Next.
3. In the Configure your new project dialog, enter HelloWorld in the Project
name box. Then choose Create.
4. We can run our program using Debug-> Start Debugging combination or Press Ctrl+F5.
5. The template creates a simple "Hello World" application. It calls
the Console.WriteLine(String) method to display "Hello World!" in the console window.
1. Open VS 2019 and on the start window, choose Create a new project.
2. Before, Language, operation system and application type are selected. After that, Choose
the Windows Form App (.NET Framework) template, and then choose Next.
3. Fill the Project Name and choose Create.
4. Congratulations. Visual Studio creates a solution for your app. A solution acts as a container
for all of the projects and files needed by your app😊. Let’s examine this picture.
About the Windows Forms Application project
If any of these windows are missing, you can restore the default window layout. On the
menu bar, choose Window > Reset Window Layout.
You can also display windows by using menu commands. On the menu bar,
choose View > Properties Window or Solution Explorer.
2. Main window In this window, you'll do most of your work, such as working with forms
and editing code. The window shows a form in the Form Editor.
Solution Explorer window In this window, you can view and navigate to all items in
your solution.
If you choose a file, the contents of the Properties window changes. If you open a code
file (which ends in .cs in C#), the code file or a designer for the code file appears. A
designer is a visual surface onto which you can add controls such as buttons and lists. For
Visual Studio forms, the designer is called the Windows Forms Designer.
Properties window In this window, you can change the properties of items that you
choose in the other windows. For example, if you choose Form1, you can change its title
by setting the Text property, and you can change the background color by setting
the Backcolor property.
3. Choose one of the following methods for running your app:
a. Choose the F5 key.
b. On the menu bar, choose Debug -> Start Debugging.
c. On the toolbar, choose the Start Debugging button.
4. Use one of the following methods to stop your app:
a. On the toolbar, choose the Stop Debugging button.
b. On the menu bar, choose Debug > Stop Debugging.
c. Use your keyboard and press Shift+F5.
d. Choose the X button in the upper corner of the Form1 window.
The shortcut key combinations commonly used in application development are as follows:
4. Variables
Variables are containers for storing data values. The variables in C#, are categorized into the following
types:
Value types: Value type variables can be assigned a value directly. They are derived from the
class System.ValueType. The value types directly contain data. Some examples are int, char,
and float, which stores numbers, alphabets, and floating point numbers, respectively. When
you declare an int type, the system allocates memory to store the value.
Reference types: The reference types do not contain the actual data stored in a variable, but
they contain a reference to the variables.
Pointer types: Pointer type variables store the memory address of another type. Pointers in
C# have the same capabilities as the pointers in C or C++.
Syntax:
To get the exact size of a type or a variable on a particular platform, you can use the sizeof() method.
data_type.MaxValue() method gives the numerical value the variable will take the most.
data_type.MinValue() method gives the numerical value the variable will take the least.
The precision of a floating point value indicates how many digits the value can have after the decimal
point. The precision of float is only six or seven decimal digits, while double variables have a
precision of about 15 digits. Therefore it is safer to use double for most calculations.
Boolean value
Textual expressions
char x = 'x';
Ex : Types
Defining Constants
Constants are defined using the const keyword.
Syntax:
using System;
namespace ConsoleApp1
{
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();
}
}
}
Local/Global Variables:
A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable it cannot be accessed. Let us understand what are local and global
variables.
Inside a function or a block which is called local variables. A local variable is used where the
scope of the variable is within the method in which it is declared. They can be used only by
statements that are inside that function or block of code.
using System;
public class Program
{
public static void Main()
{
int a;
a = 100;
// local variable
Console.WriteLine("Value:" + a);
}
}
Outside of all functions which is called global variables. A global variable is a variable
accessible anywhere, for example a field "counter" type integer. The global variable can be
accessed from any function or class within the namespace.
C# is an object-oriented programming (OOP) language and does not support global variables
directly. You need to add the static keyword before class and type.
Homework 1:
using System;
namespace ConsoleApp1
{
class Bread
{
public int counter;
}
class Program
{
static void Main(string[] args)
{
// instance of class "Butter" required
Bread a = new Bread();
a.counter = 5;
Console.WriteLine("Bread: " + a.counter);
// no instance required!
Butter.counter = 7;
Console.WriteLine("Butter: " + Butter.counter);
}
}
}
CHAPTER 5
5. Operators
Expressions are constructed from operands and operators. The operators of an expression indicate
which operations to apply to the operands. An operator is a symbol that tells the compiler to perform
specific mathematical or logical manipulations. C# has rich set of built-in operators and provides the
following type of operators [19]:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assume if A = 60; and B = 13; then in the binary format they are as follows:
A = 0011 1100
B = 0000 1101
There are few other important operators including sizeof, typeof and ? : supported by C#.
Operator Precedence in C#
Operator precedence determines the grouping of terms in an expression. This affects evaluation of an
expression. Certain operators have higher precedence than others; for example, the multiplication
operator has higher precedence than the addition operator.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear
at the bottom. Within an expression, higher precedence operators are evaluated first.
Homework 2:
CHAPTER 6
6. Type Conversions
C# type casting is also known as C# type conversion, or converting one type of data to another type. In
C#, type casting has two forms:
Implicit type casting (automatic type casting): Basically in this type of casting, C# automatically
converts smaller type into larger type, if needed, like int --> float or float --> double
Console.WriteLine(myInt); // Outputs 20
Console.WriteLine(myDouble); // Outputs 20
Explicit type casting (manual type casting): In this user provide code to convert larger type into
smaller type manually, like double --> float or float to int
Here is the list of all the built-in type casting methods available in C#.
Method Description
Convert.ToBoolean(value) Converts a value to a Boolean value, where possible.
Convert.ToByte(value) Converts a value to a byte.
Convert.ToChar(value) Converts a value to a char.
Convert.ToDecimal(value) Converts a value to decimal type.
Convert.ToDouble(value) Converts a value type to a double type.
Convert.ToInt16(value) Converts a value type to a 16-bit integer.
Convert.ToInt32(value) Converts a type to a 32-bit integer.
Convert.ToInt64(value) Converts a type to a 64-bit integer.
Convert.ToSingle(value) Converts a type to a small floating point number.
Convert.ToString(value) Converts a type to a string.
Convert.ToType(value) Converts a type to a specified type.
Convert.ToDatime(value) Convert a value to datetime type value.
Ex: DatatypeConversion
using System;
namespace DatatypeConversion
{
public class Program
{
public static void Main(string[] args)
{
int myInt = 100;
double myDouble = 2.25;
bool myBool = true;
For implicit type casting, C# 3.0 also introduced the implicit typed local variable “var”. Var can only
be defined in a method as a local variable. The compiler will infer its type based on the value to the
right of the "=" operator. Example:
using System;
namespace DataTypeCSharp
{
public class Program
{
public static void Main(string[] args)
{
var i = 10;
Console.WriteLine("Type of i is {0}", i.GetType().ToString());
var d = 10.50d;
Console.WriteLine("Type of d is {0}", d.GetType().ToString());
}
}
Result:
Type of i is System.Int32
Type of str is System.String
Type of d is System.Double
Homework 3:
CHAPTER 7
C# provides many decision-making statements that help the flow of the C# program based on certain
logical conditions.
Decision making structures requires the programmer to specify one or more conditions to be evaluated
or tested by the program, along with a statement or statements to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is determined to
be false.
Following is the general form of a typical decision making structure found in most of the
programming languages:
If Statements: At runtime, if a boolean condition evaluates to true, then the code block will
be executed, otherwise not.
Syntax: if(condition)
{
// code block to be executed when if condition evaluates to true
}
If- else Statement: Multiple else if statements can be used after an if statement. It will only be
executed when the if condition evaluates to false. So, either if or one of the else if statements
can be executed, but not both.
Syntax:
if (condition1)
{
// code block to be executed when if condition1 evaluates to true
}
else
{
// code block to be executed when
// condition1 evaluates to flase evaluates to true
}
using System;
//if condition
if (a > 20)
{
//code to be executed if condition is met true
Console.WriteLine("a is greater than 20");
}
else
{
//this will be printed, as a is less than 20
Console.WriteLine("a is less than 20");
}
}
}
else Statement
The else statement can come only after if or else if statement and can be used only once in the if-else
statements. The else statement cannot contain any condition and will be executed when all the
previous if and else if conditions evaluate to false.
Ex:
if (i > j)
{
Console.WriteLine("i is greater than j");
}
else if (i < j)
{
Console.WriteLine("i is less than j");
}
else
{
Console.WriteLine("i is equal to j");
}
Nested if Statements
C# supports if else statements inside another if else statements. This are called nested if else
statements. The nested if statements make the code more readable.
Syntax:
if(condition1)
{
if(condition2)
{
// code block to be executed when
// condition1 and condition2 evaluates to true
}
else if(condition3)
{
if(condition4)
{
// code block to be executed when
// only condition1, condition3, and condition4 evaluates to true
}
else if(condition5)
{
// code block to be executed when
// only condition1, condition3, and condition5 evaluates to true
}
else
{
// code block to be executed when
// condition1, and condition3 evaluates to true
// condition4 and condition5 evaluates to false
}
}
}
Ex:
if (i != j)
{
if (i < j)
{
Console.WriteLine("i is less than j");
}
else if (i > j)
{
Console.WriteLine("i is greater than j");
}
}
else
Console.WriteLine("i is equal to j");
Ternary Operator ?:
C# includes a decision-making operator ?: which is called the conditional operator or ternary operator.
It is the short form of the if else conditions. The ternary operator starts with a boolean condition. If this
condition evaluates to true then it will execute the first statement after ?, otherwise the second
statement after : will be executed.
Syntax:
Syntax:
switch(match expression/variable)
{
case constant-value:
statement(s) to be executed;
break;
default:
statement(s) to be executed;
break;
}
Ex:
int x = 10;
switch (x)
{
case 5:
Console.WriteLine("Value of x is 5");
break;
case 10:
Console.WriteLine("Value of x is 10");
break;
case 15:
Console.WriteLine("Value of x is 15");
break;
default:
Console.WriteLine("Unknown value");
break;
}
Syntax:
{ //code block
The for loop contains the following three optional sections, separated by a semicolon:
Initializer: The initializer section is used to initialize a variable that will be local to a for loop and
cannot be accessed outside loop. It can also be zero or more assignment statements, method call,
increment, or decrement expression e.g., ++i or i++, and await expression.
Condition: The condition is a boolean expression that will return either true or false. If an expression
evaluates to true, then it will execute the loop again; otherwise, the loop is exited.
Iterator: The iterator defines the incremental or decremental of the loop variable.
Ex:
Since all three sections are optional in the for loop, be careful in defining a condition and iterator.
Otherwise, it will be an infinite loop that will never end the loop.
for ( ; ; )
{
Console.Write(1);
}
In C# instead of breaking the complete loop, if we want to skip a iteration based on a condition then
we can use continue statement. Continue statement, will skip all the code statements if a condition is
true for a particular loop iteration.
So, continue statement causes all remaining code statements in a loop to be skipped, and execution
returns to the top of the loop.
Output:
Syntax:
While(condition)
{ //code blocks
The while loop starts with the while keyword, and it must include a boolean conditional expression
inside brackets that returns either true or false. It executes the code block until the specified
conditional expression returns false. The for loop contains the initialization and increment/decrement
parts. When using the while loop, initialization should be done before the loop starts, and increment or
decrement steps should be inside the loop.
int i = 0; // initialization
i++; // increment
}
Use the break keyword to exit from a while loop on some condition.
int i = 0;
while (true)
{
Console.WriteLine("i = {0}", i);
i++;
if (i > 10)
break;
}
For the while and do-while loops, continue statement causes the program control passes to the
conditional tests.
int i = 0;
while (i >= 0)
{
Console.WriteLine("i = {0}", i);
i++;
}
C# allows while loops inside another while loop, as shown below. However, it is not recommended to
use nested while loop because it makes it hard to debug and maintain.
int i = 0, j = 1;
while (i < 2)
{
Console.WriteLine("i = {0}", i);
i++;
while (j < 2)
{
Console.WriteLine("j = {0}", j);
j++;
}
}
int i = 0; i = 0
i = 1
do i = 2
{ i = 3
Console.WriteLine("i = {0}", i); i = 4
i++;
int i = 0;
do
{
Console.WriteLine("i = {0}", i);
i++;
if (i > 5)
break;
} while (i < 10);
Nested do-while
The do-while loop can be used inside another do-while loop.
int i = 0;
do
{
Console.WriteLine("Value of i: {0}", i);
int j = i;
i++;
do
{
Console.WriteLine("Value of j: {0}", j);
j++;
} while (j < 2);
CHAPTER 8
8. Arrays [21]
A variable is used to store a literal value, whereas an array is used to store multiple literal values. An
array is the data structure that stores a fixed number of literal values (elements) of the same data type.
Array elements are stored contiguously in the memory.
In C#, an array can be of three types: single-dimensional, multidimensional, and jagged array.
Single dimensional,
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.
Initializing an Array;
Declaring an array does not initialize the array in the memory. When the array variable is initialized,
you can assign values to the array.
You can assign values to individual array elements, by using the index number;
balance[0] = 4500.0;
You can copy an array variable into another target array variable. In such case, both the target and
source point to the same memory location.
int [] marks = new int[] { 99, 98, 92, 97, 95};
int[] score = marks;
Ex:
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;
Syntax:
Ex:
// or
int[,] arr2d = {
{1, 2},
{3, 4},
{5, 6}
};
Ex: You can pass an array as a function argument in C#. The following example demonstrates:
using System;
namespace ArrayApplication
{
class MyArray
{
double getAverage(int[] arr, int size)
{
int i;
double avg;
int sum = 0;
Array Class
The Array class is the base class for all the arrays in C#. It is defined in the System namespace. The
Array class provides various properties and methods to work with arrays.
o Properties of the Array Class
The following table describes some of the most commonly used properties of the Array class.
Property Description
IsFixedSize Gets a value indicating whether the Array has a fixed size.
IsReadOnly Gets a value indicating whether the Array is read-only.
Length Gets a 32-bit integer that represents the total number of elements in all the
dimensions of the Array.
LongLength Gets a 64-bit integer that represents the total number of elements in all the
dimensions of the Array.
Rank Gets the rank (number of dimensions) of the Array.
The following table describes some of the most commonly used methods of the Array class.
Methods Desciption
Clear Sets a range of elements in the Array to zero, to false, or to null,
depending on the element type.
Copy(Array, Array, Int32) Copies a range of elements from an Array starting at the first
element and pastes them into another Array starting at the first
element. The length is specified as a 32-bit integer.
CopyTo(Array, Int32) Copies all the elements of the current one-dimensional Array to
the specified one-dimensional Array starting at the specified
destination Array index. The index is specified as a 32-bit
integer.
GetLength Gets a 32-bit integer that represents the number of elements in
the specified dimension of the Array.
GetLongLength Gets a 64-bit integer that represents the number of elements in
the specified dimension of the Array.
GetLowerBound Gets the lower bound of the specified dimension in the Array.
GetUpperBound Gets the upper bound of the specified dimension in the Array.
GetValue(Int32) Gets the value at the specified position in the one-dimensional
Array. The index is specified as a 32-bit integer.
IndexOf(Array, Object) Searches for the specified object and returns the index of the
first occurrence within the entire one-dimensional Array.
SetValue(Object, Int32) Sets a value to the element at the specified position in the one-
dimensional Array. The index is specified as a 32-bit integer.
Ex:
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int[] list = { 34, 72, 13, 44, 25, 30, 10 };
int[] temp = list;
Console.Write("Original Array: ");
9. Enum
In C#, an enum (or enumeration type) is used to assign constant names to a group of numeric integer
values. It makes constant values more readable, for example, WeekDays.Monday is more readable
then number 0 when referring to the day in a week.
An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the
constant names can be declared inside the curly brackets and separated by a comma.
Syntax:
enum <enum_name> { enumeration list };
enum Days { Monday, //0
Tuesday, //1
Wednesday, //2
};
enum Categories
{ Electronics = 1,
Food = 5,
}
The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong.
However, an enum cannot be a string type.
enum WeekDays
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
Console.WriteLine(WeekDays.Monday); // Monday
Console.WriteLine(WeekDays.Tuesday); // Tuesday
Console.WriteLine(WeekDays.Wednesday); // Wednesday
Explicit casting is required to convert from an enum type to its underlying integral type.
enum WeekDays
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
Ex:
using System;
namespace EnumApplication
{
class EnumProgram
{
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
Method Description
GetName(Type, Object) Retrieves the name of the constant in the
specified enumeration that has the specified
value.
GetNames(Type) Retrieves an array of the names of the constants
in a specified enumeration.
IsDefined(Type, Object) Returns a Boolean telling whether a given
integral value, or its name as a string, exists in a
specified enumeration.
Parse(Type, String, Boolean) Converts the string representation of the name or
numeric value of one or more enumerated
constants to an equivalent enumerated object. A
parameter specifies whether the operation is
case-insensitive.
10. Collections
C# includes specialized classes that store series of values or objects are called collections. There are
two types of collections available in C#: non-generic collections and generic collections.
In most cases, it is recommended to use the generic collections because they perform faster than non-
generic collections and also minimize exceptions by giving compile-time errors.
Generic Collections
ArrayList
In C#, the ArrayList is a non-generic collection of objects whose size increases dynamically. It is the
same as Array except that its size increases dynamically.
An ArrayList can be used to add unknown data where you don't know the types and the size of the
data. The following diagram illustrates the ArrayList class.
Properties Description
Capacity Gets or sets the number of elements that the ArrayList can
contain.
Count Gets the number of elements actually contained in the ArrayList.
IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.
IsReadOnly Gets a value indicating whether the ArrayList is read-only.
Item Gets or sets the element at the specified index.
Methods Description
Add()/AddRange() Add() method adds single elements at the end of ArrayList.
Insert()/InsertRange() Insert() method insert a single elements at the specified index in
ArrayList.
Remove()/RemoveRange() Remove() method removes the specified element from the
ArrayList.
RemoveAt() Removes the element at the specified index from the ArrayList.
Sort() Sorts entire elements of the ArrayList.
Reverse() Reverses the order of the elements in the entire ArrayList.
Contains Checks whether specified element exists in the ArrayList or not.
Returns true if exists otherwise false.
Clear Removes all the elements in ArrayList.
CopyTo Copies all the elements or range of elements to compitible
Array.
GetRange Returns specified number of elements from specified index from
ArrayList.
IndexOf Search specified element and returns zero based index if found.
Returns -1 if element not found.
ToArray Returns compitible array from an ArrayList.
o Create an ArrayList
The ArrayList class included in the System.Collections namespace. Create an object of the ArrayList
using the new keyword.
Syntax:
using System.Collections;
Use the Add(object) method or object initializer syntax to add elements in an ArrayList. An ArrayList
can contain multiple null and duplicate values.
Syntax:
Accessing an ArrayList
The ArrayList class implements the IList interface. So, elements can be accessed using indexer, in
the same way as an array. Index starts from zero and increases by one for each subsequent element. An
explicit casting to the appropriate types is required, or use the var variable.
//update elements
arlist[0] = "Steve";
arlist[1] = 100;
//arlist[5] = 500; //Error: Index out of range
o Iterate an ArrayList
The ArrayList implements the ICollection interface that supports iteration of the collection types. So,
use the foreach and the for loop to iterate an ArrayList. The Count property of an ArrayList returns
the total number of elements in an ArrayList.
Use the Insert() method to insert an element at the specified index into an ArrayList.
Syntax:
void Insert(int index, Object value)
ArrayList list_1 = new ArrayList()
{
1,
"Bill",
300,
4.5f
};
Use the InsertRange() method to insert a collection in an ArrayList at the specfied index.
Syntax: Void InsertRange(int index, ICollection c)
ArrayList arlist1 = new ArrayList()
{
100, 200, 600
};
Use the Remove(), RemoveAt(), or RemoveRange methods to remove elements from an ArrayList.
Use the Contains() method to determine whether the specified element exists in the ArrayList or not. It
returns true if exists otherwise returns false.
Console.WriteLine(arList.Contains(300)); // true
Console.WriteLine(arList.Contains("Bill")); // true
Console.WriteLine(arList.Contains(10)); // false
Console.WriteLine(arList.Contains("Steve")); // false
using System;
using System.Collections;
namespace List_Example
{
class Program
{
static void Main(string[] args)
{
ArrayList list_1 = new ArrayList();
//var list_1 = new ArrayList();
//update elements
list_1[0] = "Steve";
list_1[1] = 100;
Console.WriteLine(arList.Contains(300)); // true
Console.WriteLine(arList.Contains("Bill")); // true
Console.WriteLine(arList.Contains(10)); // false
Console.WriteLine(arList.Contains("Steve")); // false
}
}
}
CHAPTER 11
11. Methods
A method is a group of statements that together perform a task. Every C# program has at least one
class with a method named Main. To use a method, you need to
Defining Methods in C#
When you define a method, you basically declare the elements of its structure.
Syntax:
<Access Specifier> <Return Type> <Method Name>(Parameter List) {
Method Body }
Access Specifier: This determines the visibility of a variable or a method from another class.
Return type: A method may return a value. The return type is the data type of the value the method
returns. If the method is not returning any values, then the return type is void.
Method name: Method name is a unique identifier and it is case sensitive. It cannot be same as any
other identifier declared in the class.
Parameter list: Enclosed between parentheses, the parameters are used to pass and receive data from
a method. The parameter list refers to the type, order, and number of the parameters of a method.
Parameters are optional; that is, a method may contain no parameters.
Method body: This contains the set of instructions needed to complete the required activity.
Ex:
class Program
{
return result;
}
...
}
Calling Methods in C#
You can call a method using the name of the method. FindMax function that takes two integer values
and returns the larger of the two. It has public access specifier, so it can be accessed from outside the
class using an instance of the class.
using System;
namespace Function_Example
{
class Program
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
You can also call public method from other classes by using the instance of the class. For example, the
method FindMax belongs to the Program class, you can call it from another class Test in the below.
using System;
namespace CalculatorApplication
{
class Program
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
return result;
}
}
class Test
{
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
Program n = new Program();
using System;
namespace Recursive_Func_Example
{
class Program
{
public 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)
{
Program n = new Program();
//calling the factorial method {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 a Method
When method with parameters is called, you need to pass the parameters to the method. There are
three ways that parameters can be passed to a method.
Parameter Description
Value parameters This method copies the actual value of an
argument into the formal parameter of the
function. In this case, changes made to the
parameter inside the function have no effect on
the argument.
Reference parameters This method copies the reference to the memory
location of an argument into the formal
parameter. This means that changes made to the
parameter affect the argument.
Output parameters This method helps in returning more than one
value.
When a method is called, a new storage location is created for each value parameter. The values of the
actual parameters are copied into them. Hence, the changes made to the parameter inside the method
have no effect on the argument.
Ex:
using System;
namespace Passing_byValue
{
class Program
{
public void swap(int x, int y)
{
int temp;
Console.ReadLine();
}
}
}
It shows that there is no change in the values though they had changed inside the function.
o Passing Parameters by Reference
A reference parameter is a reference to a memory location of a variable. When you pass parameters by
reference, unlike value parameters, a new storage location is not created for these parameters. The
reference parameters represent the same memory location as the actual parameters that are supplied to
the method. You can declare the reference parameters using the ref keyword.
Ex:
using System;
namespace Passing_byReference
{
class Program
{
public void swap(ref int x, ref int y)
{
int temp;
Console.ReadLine();
}
}
}
It shows that the values have changed inside the swap function and this change reflects in the Main
function.
A return statement can be used for returning only one value from a function. However, using output
parameters, you can return two values from a function. Output parameters are similar to reference
parameters, except that they transfer data out of the method rather than into it.
Ex:
using System;
namespace PAssing_byOutput
{
class Program
{
public void getValue(out int x)
{
int temp = 5;
x = temp;
}
static void Main(string[] args)
{
Program n = new Program();
Ex:
using System;
namespace Passing_byOutputfromFunc
{
class Program
{
public void getValues(out int x, out int y)
{
Console.WriteLine("Enter the first value: ");
x = Convert.ToInt32(Console.ReadLine());
Syntax:
DateTime dt = new DateTime(); // assigns default value 01.01.0001
00:00:00
Use different constructors of the DateTime struct to assign an initial value to a DateTime object.
Ex:
using System;
namespace DateTimeObject
{
class Program
{
static void Main(string[] args)
{
DateTime dt = new DateTime(); // assigns default value 01.01.0001
00:00:00
Console.WriteLine(dt);
}
}
}
In the above example, we specified a year, a month, and a day in the constructor. The year can be from
0001 to 9999, and the Month can be from 1 to 12, and the day can be from 1 to 31. Setting any other
value out of these ranges will result in a run-time exception.
The DateTime struct includes static fields, properties, and methods. The following example
demonstrates important static fields and properties.
time DateTime.Now;
DayOfWeek gets the day of the week DateTime dt7 = new DateTime(2020,
9, 6);
represented by this Console.WriteLine(dt7.
instance DayOfWeek);
DayOfYear gets the day of the year DateTime dt7 = new DateTime(2020,
9, 6);
represented by this Console.WriteLine(dt7.DayOfYear);
instance
Hour gets the instance hour DateTime Dtclock = DateTime.Now;
Console.WriteLine(Dtcl
ock.Hour);
represented instance
UtcNow returns current UTC date DateTime currentDateTimeUTC =
DateTime.UtcNow;
and time
MaxValue returns max value of DateTime maxDateTimeValue =
DateTime.MaxValue;
DateTime
MinValue returns min value of DateTime minDateTimeValue =
DateTime.MinValue;
DateTime
Ticks TimeSpan ToLongDateString()
Add() TotalDays ToLongTimeString()
AddDays() TotalHours ToShortDateString()
AddHours() Seconds ToShortTimeString()
AddMilisecond() TotalMinutes DayIsMonth(,)
AddMinutes() TotalMiliSeconds IsleapYear()
AddMonts TimeSpan CompareTo(DateTime )
AddSeconds() TotalDays ToString(string )
AddYears() TotalHours Parse(string)
ToLongDateString() ToLongTimeString()
TimeSpan
TimeSpan is a struct that is used to represent time in days, hour, minutes, seconds, and milliseconds.
Ex:
DateTime dt4 = new DateTime(2015, 12, 31);
Console.WriteLine(newDate);
o Operators
The DateTime struct overloads +, -, ==, !=, >, <, <=, >= operators to ease out addition,
subtraction, and comparison of dates. These make it easy to work with dates.
if (isValidDate)
Console.WriteLine(dt);
else
Console.WriteLine($"{str} is not a valid date string");
CHAPTER 13
13. Math Class
The C# Math class has many methods that allows you to perform mathematical tasks on numbers.
Math class comes under the System namespace. It is used to provide static methods and constants for
logarithmic, trigonometric, and other useful mathematical functions. It is a static class and inherits the
object class.
public static class Math class contains the two fields i.e. E and PI.
Math.E Field: This field represents the natural logarithmic base, specified by the constant, e.
Math.PI Field: It represents the ratio of the circumference of a circle to its diameter, specified
by the constant, PI(π).
Ex:
using System;
namespace Math_Pi_E
{
class Program
{
static void Main(string[] args)
{
// To find E constant values
double e = Math.E;
// Print result
Console.WriteLine("Math.E = " + e);
// Print result
Console.WriteLine("Math.PI = " + pi_value);
}
}
}
Math class contains methods:
Method Description
Abs() Returns the absolute value of a specified number.
Acos() Returns the angle whose cosine is the specified number.
Acosh() Returns the Inverse hyperbolic cosine of the specified number.
Asin() Returns the angle whose sine is the specified number.
Asinh() Returns the Inverse hyperbolic sine of the specified number.
Atan() Returns the angle whose tangent is the specified number.
Atanh() Returns the Inverse hyperbolic tangent of the specified number.
BigMul() Produces the full product of two 32-bit numbers.
Cbrt() Returns the cube root of a specified value.
Returns the smallest integral value greater than or equal to the
Ceiling() specified number.
Clamp() It is used to restrict a value to a given range.
Cos() Returns the cosine of the specified angle.
Cosh() Returns the hyperbolic cosine of the specified angle.
Calculates the quotient of two numbers and also returns the
DivRem() remainder in an output parameter.
Exp() Returns e raised to the specified power.
Returns the largest integral value less than or equal to the specified
Floor() number.
Returns the remainder resulting from the division of a specified
IEEERemainder() number by another specified number.
Log() Returns the logarithm of a specified number.
Log10() Returns the base 10 logarithm of a specified number.
Max() Returns the larger of two specified numbers.
Min() Returns the smaller of two numbers.
Pow() Returns a specified number raised to the specified power.
Rounds a value to the nearest integer or to the specified number of
Round() fractional digits.
Sign() Returns an integer that indicates the sign of a number.
Sin() Returns the sine of the specified angle.
Sinh() Returns the hyperbolic sine of the specified angle.
Sqrt() Returns the square root of a specified number.
Tan() Returns the tangent of the specified angle.
Tanh() Returns the hyperbolic tangent of the specified angle.
Truncate() Calculates the integral part of a number.
using System;
namespace MAth_Methods
{
class Program
{
static void Main(string[] args)
{
// using Floor() Method
Console.WriteLine("Floor value of 123.123: "
+ Math.Floor(123.123));
Class Objects
Apple
Car Banana
Strawberry
So, a class is a template for objects, and an object is an instance of a class. When the individual objects
are created, they inherit all the variables and methods from the class.
Everything in C# is associated with classes and objects, along with its attributes and methods. For
example: in real life, a car is an object. The car has attributes, such as weight and color, and methods,
such as drive and brake.
Create a Class
To create a class, use the class keyword:
When a variable is declared directly in a class, it is often referred to as a field (or attribute)
Create an Object
An object is created from a class. We have already created the class named Car, so now we can use
this to create objects. To create an object of Car, specify the class name, followed by the object name,
and use the keyword new. Create an object called “myObj” and use it to print the value of color:
Ex:
using System;
namespace Create_Obj_Class
{
class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}
}
You can also create an object of a class and access it in another class. This is often used for better
organization of classes (one class has all the fields and methods, while the other class holds the Main()
method). Car.cs and Program.cs
Car.cs
using System;
namespace MyApplication
{
class Car
{
public string color = "red";
}
}
Program.cs
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}
}
The color variable/field of Car is accessible for other classes as well, such as Program.So, we must use
“public” access modifier.
Class Members
Fields and methods inside classes are often referred to as "Class Members". For example, Create a Car
class with three class members: two fields and one method.
class MyClass
{
// Class members
string color = "red"; // field
int maxSpeed = 200; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
}
Fields
The variables inside a class are called fields, and that you can access them by creating an object of the
class, and by using the dot syntax (.).
The following example will create an object of the Car class, with the name myObj. Then we print the
value of the fields color and maxSpeed:
class Car
{
string color = "red";
int maxSpeed = 200;
namespace MyApplication
{
class Car
{
string model;
string color;
int year;
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}
}
Object Methods
Methods normally belongs to a class, and they define how an object of a class behaves. Just like with
fields, you can access methods with the dot syntax. However, note that the method must be public.
And remember that we use the name of the method followed by two parantheses () and a semicolon; to
call the method.
Ex:
using System;
namespace Create_Methods_Class
{
class Car
{
string color; // field
int maxSpeed; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
We declare the method as public, and not static .The reason is simple: a static method can be accessed
without creating an object of the class, while public methods can only be accessed by objects.
Constructors
A constructor is a special method that is used to initialize objects. The advantage of a constructor, is
that it is called when an object of a class is created. It can be used to set initial values for fields.
Ex:
using System;
namespace Create_Constructor
{
// Create a Car class
class Car
{
public string model; // Create a field
Note that the constructor name must match the class name, and it cannot have a return type (like void
or int). Also note that the constructor is called when the object is created. All classes have constructors
by default: if you do not create a class constructor yourself, C# creates one for you. However, then you
are not able to set initial values for fields. Constructors save time!
Constructor Parameters
The following example adds a string modelName parameter to the constructor. Inside the constructor
we set model to modelName (model=modelName). When we call the constructor, we pass a
parameter to the constructor ("Mustang"), which will set the value of model to “Mustang”.
Ex:
using System;
namespace Create_Constructor_Parameter
{
class Car
{
public string model;
public string color;
public int year;
When you consider the example from the previous chapter, you will notice that constructors are very
useful, as they help reducing the amount of code:
Console.WriteLine(Opel.model);
}
}
Access Modifiers
Modifier Description
public The code is accessible for all classes
private The code is only accessible within the same
class
protected The code is accessible within the same class, or
in a class that is inherited from that class. You
will learn more about inheritance in a later
chapter
internal The code is only accessible within its own
assembly, but not from another assembly. You
will learn more about this in a later chapter
o Private Modifier
If you declare a field with a private access modifier, it can only be accessed within the same class. By
default, all members of a class are private if you don't specify an access modifier. To achieve
"Encapsulation" - which is the process of making sure that "sensitive" data is hidden from users. This
is done by declaring fields as private.
using System;
namespace MyApplication
{
class Car
{
private string model = "Mustang";
Car.cs Program.cs
using System; using System;
Console.WriteLine(myObj.model);
}
}
}
o Public Modifier
If you declare a field with a public access modifier, it is accessible for all classes.
Car.cs Program.cs
using System; using System;
Console.WriteLine(myObj.model);
}
}
}
Encapsulation is to make sure that sensitive data is hidden from users. To achieve this:
o Properties
Private variables can only be accessed within the same class (an outside class has no access to it).
However, sometimes we need to access them - and it can be done with properties. A property is like a
combination of a variable and a method, and it has two methods: a get and a set method.
Ex:
Person.cs Program.cs
using System; using System;
The Name property is associated with the name field. It is a good practice to use the same name for
both the property and the private field, but with an uppercase first letter. The get method returns the
value of the variable name. The set method assigns a value to the name variable. The value keyword
represents the value we assign to the property. We can use the Name property to access and update the
private field of the Person class
o Automatic Properties
C# also provides a way to use short-hand / automatic properties, where you do not have to define the
field for the property, and you only have to write get; and set; inside the property. The following
example will produce the same result as the example above. The only difference is that there is less
code:
Ex:
Person.cs Program.cs
using System; using System;
Console.WriteLine(myObj.Name);
}
}
}
Better control of class members (reduce the possibility of yourself (or others) to mess up the
code)
Fields can be made read-only (if you only use the get method), or write-only (if you only use
the set method)
Flexible: the programmer can change one part of the code without affecting other parts
Increased security of data
Inheritance
It is possible to inherit fields and methods from one class to another. We group the “inheritance
concept” into two categories:
Derived Class (child): the class that inherits from another class
Base Class (parent): the class being inherited from
To inherit from a class, use the : symbol. It is useful for code reusability: reuse fields and methods of
an existing class when you create a new class.
In the example below, the Car class (child) inherits the fields and methods from the Vehicle class
(parent):
Ex:
Console.WriteLine(myCar.br
and + " " +
myCar.modelName);
}
}
}
If you don't want other classes to inherit from a class, use the sealed keyword.
Polymorphism
Polymorphism means “many forms”, and it occurs when we have many classes that are related to each
other by inheritance. Inheritance lets us inherit fields and methods from another class. Polymorphism
uses those methods to perform different tasks. This allows us to perform a single action in different
ways.
For example, think of a base class called Animal that has a method called animalSound(). Derived
classes of Animals could be Pigs, Cats, Dogs, Birds. And they also have their own implementation of
an animal sound (the pig oinks, and the cat meows, etc.).
Ex:
using System;
namespace Polymorphism
{
class Animal // Base class (parent)
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
}
Abstraction
Data abstraction is the process of hiding certain details and showing only essential information to the
user. The abstract keyword is used for classes and methods.
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is
provided by the derived class (inherited from).
Ex:
using System;
namespace Abstract
{// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
}
CHAPTER 15
15. Windows Form Application Creating
When you create a Windows Forms App project, you actually build a program that runs. For now, it
displays an empty window that shows Form1 in the title bar.
2. Visual Studio runs your app, and a window called Form1 appears. The following screenshot shows
the app you just built.
3. Go back to the Visual Studio integrated development environment (IDE), and then look at the new
toolbar. Additional buttons appear on the toolbar when you run an application. These buttons let you
do things like stop and start your app, and help you track down any errors (bugs) it may have. For this
example, we're using it to start and stop the app.
1. Form
You can see a default Form (Form1) in the new C# project. The Windows Form you see in Designer
view is a visual representation of the window that will open when your application is opened.
At the top of the form there is a title bar which displays the forms title. Form1 is the default name, and
you can change the name to your convenience. The title bar also includes the control box, which holds
the minimize, maximize, and close buttons.If you want to set any properties of the Form, you can use
Visual Studio Property window to change it. If you do not see the Properties window, on the View
menu, click Properties window. This window lists the properties of the currently selected Windows
Form or control, and its here that you can change the existing values.
To change the forms title from Form1 to MyForm, click on Form1 and move to the right side down
Properties window, set Text property to MyForm. Then you can see the Title of the form is changed.
Likewise you can set any properties of Form through Properties window.
You can also set the properties of the Form1 through coding. For coding, you should right-click the
design surface or code window and then clicking View Code [23].
When you right click on Form then you will get code behind window, there you can write your code.
Locate the toolbox on the side of the Form1. If the toolbox is not visible, pull down the View menu
and select Toolbox. Drag and drop an item from the tool box to the form.
Detailed descriptions of each feature and event can be found in Microsoft documentation [24].
2. Button [25]
A Button is an essential part of an application, or software, or webpage. It allows the user to interact
with the application or software. For example, if a user wants to exit from the current application so,
he/she click the exit button which closes the application. It can be used to perform many actions like to
submit, upload, download, etc. according to the requirement of your program. It can be available with
different shape, size, color, etc. and you can reuse them in different applications. In .NET Framework,
Button class is used to represent windows button control and it is inherited from ButtonBase class. It is
defined under System.Windows.Forms namespace.
In C# you can create a button on the windows form by using two different ways:
1. Design-Time: It is the easiest method to create a button. Use the below steps:
Step 1: Create a windows form.
Step 2: Drag the Button control from the ToolBox and drop it on the windows form. You are
allowed to place a Button control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the Button control to set the properties of
the Button.
2. Run-Time You can create your own Button using the Button class.
Step 1: Create a button using the Button() constructor is provided by the Button class.
// Creating Button using Button class
Button MyButton = new Button();
Step 2: After creating Button, set the properties of the Button provided by the Button class.
Step 3: And last add this button control to form using Add() method.
PROPERTY DESCRIPTION
Using BackColor property you can set the background color of the
BackColor button.
Using AutoEllipsis property you can set a value which shows that
whether the ellipsis character (…) appears at the right edge of the
control which denotes that the button text extends beyond the specified
AutoEllipsis length of the button.
Using AutoSize property you can set a value which shows whether the
AutoSize button resizes based on its contents.
Using Enabled property you can set a value which shows whether the
Enabled button can respond to user interaction.
Using Events property you can get the list of the event handlers that are
Events applied on the given button.
Font Using Font property you can set the font of the button.
FontHeight Using FontHeight property you can set the height of the font.
Using ForeColor property you can set the foreground color of the
ForeColor button.
Height Using Height property you can set the height of the button.
Image Using Image property you can set the image on the button.
Margin Using Margin property you can set the margin between controls.
Name Using Name property you can set the name of the button.
Padding Using Padding property you can set the padding within the button.
Visible Using Visible property you can set a value which shows whether the
button and all its child buttons are displayed.
EVENT DESCRIPTION
Click This event occur when the button is clicked.
This event occur when the user performs
DoubleClick double click on the button.
This event occur when the control is
Enter entered.
This event occur when the character, or
space, or backspace key is pressed while
KeyPress the control has focus.
This event occur when the input focus
Leave leaves the control.
This event occur when you click the mouse
MouseClick pointer on the button.
This event occur when you double click the
MouseDoubleClick mouse pointer on the button.
This event occur when the mouse pointer
MouseHover placed on the button.
MouseLeave This event occur when the mouse pointer
leaves the button.
Ex:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormApp_Introduction
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
3. TextBox
In Windows forms, TextBox plays an important role. With the help of TextBox, the user can enter data
in the application, it can be of a single line or of multiple lines. In TextBox, you are allowed to set the
text associated with the TextBox by using the Text property of the TextBox. In Windows form, you
can set this property in two different ways:
1. Design-Time: It is the simplest way to set the Text property of the TextBox as shown in the
following steps:
Step 1: Create a windows form.
Step 2: Drag the TextBox control from the ToolBox and Drop it on the windows form.
You can place TextBox anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the TextBox control to set the
Text property of the TextBox.
2. Run-Time: Following steps are used to set the Text property of the TextBox:
Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.
// Creating textbox
TextBox Mytextbox = new TextBox();
Step 2 : After creating TextBox set the Text property of the TextBox provided by the TextBox class.
Step 3 : And last add this textbox control to from using Add() method.
PROPERTY DESCRIPTION
This property is used to set a value which shows
whether pressing ENTER in a multiline TextBox
control creates a new line of text in the control
or activates the default button for the given
AcceptsReturn form.
This property is used to adjust the size of the
AutoSize TextBox according to the content.
This property is used to set the background color
BackColor of the TextBox.
This property is used to adjust the border type of
BorderStyle the textbox.
This property is used to check whether the
TextBox control modifies the case of characters
CharacterCasing as they are typed.
This property is used to provide a list of event
Events handlers that are attached to this Component.
This property is used to adjust the font of the
Font text displayed by the textbox control.
This property is used to adjust the foreground
ForeColor color of the textbox control.
This property is used to adjust the coordinates of
the upper-left corner of the textbox control
Location relative to the upper-left corner of its form.
Margin This property is used to set the margin between
two textbox controls.
This property is used to set the maximum
number of characters the user can type or paste
MaxLength into the text box control.
This property is used to set a value which shows
Multiline whether this is a multiline TextBox control.
This property is used to provide a name to the
Name TextBox control.
This property is used to set the character used to
mask characters of a password in a single-line
PasswordChar TextBox control.
This property is used to set which scroll bars
ScrollBars should appear in a multiline TextBox control.
This property is used to set the text associated
Text with this control.
This property is used to adjust the alignment of
the text in the TextBox control.
TextAlign
This property is used to get the length of the text
TextLength in the TextBox control.
This property is used to set a value which shows
whether the text in the TextBox control should
UseSystemPasswordChar appear as the default password character.
This property is used to get or set a value which
determine whether the control and all its child
Visible controls are displayed.
namespace TextBox_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
namespace my
{
namespace ScrolbarTexrbox_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
namespace TextboxPassword_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
4. Label
In Windows Forms, Label control is used to display text on the form and it does not take part in user
input or in mouse or keyboard events. The Label is a class and it is defined under
System.Windows.Forms namespace.
Important Properties of the Label Control
PROPERTY DESCRIPTION
This property is used to set a value indicating whether the Label
AutoSize control is automatically resized to display its entire contents.
This property is used to set the background color for the Label
BackColor control.
This property is used to set the background image for the Label
BackgroundImage control.
BorderStyle This property is used to set the border style for the Label control.
This property is used to set the flat style appearance of the label
FlatStyle control.
This property is used to set the font of the text displayed by the
Font Label control.
This property is used to set the height of the font of the Label
FontHeight control.
This property is used to set the foreground color of the Label
ForeColor control.
Height This property is used to set the height of the Label control.
This property is used to set the image that is displayed on a
Image Label.
This property is used to set the coordinates of the upper-left
corner of the Label control relative to the upper-left corner of its
Location form.
Name This property is used to set the name of the Label control.
Padding This property is used to set padding within the Label control.
This property is used to set the height and width of the Label
Size control.
This property is used to set the text associated with this Label
Text control.
TextAlign This property is used to set the alignment of text in the label.
This property is used to set a value indicating whether the
Visible control and all its child controls are displayed.
Width This property is used to set the width of the Label control.
Ex:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Label_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
5. RadioButton
In Windows Forms, RadioButton control is used to select a single option among the group of the
options. For example, select your gender from the given list, so you will choose only one option
among three options like Male or Female. In C#, RadioButton is a class and it is defined under
System.Windows.Forms namespace. In RadioButton, you are allowed to display text, image, or both
and when you select one radio button in a group other radio buttons automatically clear.
Important Properties
PROPERTY DESCRIPTION
This property is used to set a value determining
Appearance the appearance of the RadioButton.
This property is used to set a value indicating
whether the Checked value and the appearance
of the RadioButton control automatically change
AutoCheck when the RadioButton control is clicked.
AutoSize This property is used to set a value that indicates
whether the RadioButton control resizes based
on its contents.
This property is used to set the background color
BackColor of the RadioButton control.
This property is used to set the location of the
CheckAlign check box portion of the RadioButton.
This property is used to set a value indicating
Checked whether the RadioButton control is checked.
This property is used to set the font of the text
Font displayed by the RadioButton control.
This property is used to set the foreground color
ForeColor of the RadioButton control.
This property is used to sets the coordinates of
the upper-left corner of the RadioButton control
Location relative to the upper-left corner of its form.
This property is used to sets the name of the
Name RadioButton control.
This property is used to sets padding within the
Padding RadioButton control.
This property is used to set the text associated
Text with this RadioButton control.
This property is used to set the alignment of the
TextAlign text on the RadioButton control.
This property is used to set a value indicating
whether the RadioButton control and all its child
Visible controls are displayed.
Important Events
EVENT DESCRIPTION
This event occurs when the RadioButton control
Click is clicked.
This event occurs when the value of the
CheckedChanged Checked property changes.
This event occurs when the Appearance property
AppearanceChanged value changes.
This event occurs when the user double-clicks
DoubleClick the RadioButton control.
This event occurs when the input focus leaves
Leave the RadioButton control.
This event occurs when the RadioButton control
MouseClick is clicked by the mouse.
This event occurs when the user double-clicks
MouseDoubleClick the RadioButton control with the mouse.
This event occurs when the mouse pointer rests
MouseHover on the RadioButton control.
Ex:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RadioButton_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
6. ComboBox
A ComboBox displays a text box combined with a ListBox, which enables the user to select items
from the list or enter a new value. The user can type a value in the text field or click the button to
display a drop down list. You can add individual objects with the Add method. You can delete items
with the Remove method or clear the entire list with the Clear method.
PROPERTY DESCRIPTION
This property is used to set the background color
BackColor for the ComboBox control.
This property is used to set the height in pixels
of the drop-down portion of the ComboBox
DropDownHeight control.
This property is used to set a value specifying
DropDownStyle the style of the ComboBox control.
DropDownWidth This property is used to set the width of the of
the drop-down portion of a ComboBox control.
This property is used to set the font of the text
Font displayed by the ComboBox control.
This property is used to set the foreground color
ForeColor of the ComboBox control.
This property is used to set the height of the
Height ComboBox control.
This property is used to get an object
representing the collection of the items
Items contained in this ComboBox control.
This property is used to set the maximum
number of items to be shown in the drop-down
MaxDropDownItems portion of the ComboBox control.
This property is used to set the number of
characters a user can type into the ComboBox
MaxLength control.
This property is used to set the name of the
Name ComboBox control.
This property is used to set currently selected
SelectedItem item in the ComboBox.
This property is used to set the height and width
Size of the ComboBox control.
This property is used to set a value indicating
Sorted whether the items in the combo box are sorted.
This property is used to set the text associated
Text with this ComboBox control.
This property is used to set a value indicating
whether the control and all its child controls are
Visible displayed.
Important Events
EVENT DESCRIPTION
This event occur when the ComboBox control is
Click clicked.
DragDrop This event occur when a drag-and-drop
operation is completed.
This event occur when the drop-down portion of
DropDown a ComboBox is shown.
This event occur when the drop-down portion of
DropDownClosed the ComboBox is no longer visible.
This event occur when the DropDownStyle
DropDownStyleChanged property has changed.
This event occur when the input focus leaves the
Leave ComboBox control.
This event occur when the ComboBox control is
MouseClick clicked by the mouse.
This event occur when the ComboBox control is
MouseDoubleClick double clicked by the mouse.
This event occur when the mouse pointer is over
the ComboBox control and a mouse button is
MouseDown pressed.
This event occur when the mouse pointer enters
MouseEnter the ComboBox control.
This event occur when the mouse pointer rests
MouseHover on the ComboBox control.
This event occur when the SelectedIndex
SelectedIndexChanged property has changed.
Ex:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Combobox_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Ex:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Combobox_2_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("weekdays");
comboBox1.Items.Add("year");
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs
e)
{
comboBox2.Items.Clear();
if (comboBox1.SelectedItem.Equals("weekdays"))
{
comboBox2.Items.Add("Sunday");
comboBox2.Items.Add("Monday");
comboBox2.Items.Add("Tuesday");
}
else if (comboBox1.SelectedItem.Equals("year"))
{
comboBox2.Items.Add("2012");
comboBox2.Items.Add("2013");
comboBox2.Items.Add("2014");
}
}
}
}
7. ListBox
The ListBox control enables you to display a list of items to the user that the user can select by
clicking.
Ex:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ListBox_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
namespace CheckedList_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
checkedListBox1.GetItemCheckState(indexChecked).ToString() + ".");
}
}
}
}
8. RichText
RichTextBox control is a textbox which gives you rich text editing controls and advanced formatting
features also includes a loading rich text format (RTF) files. Or in other words, RichTextBox controls
allows you to display or edit flow content, including paragraphs, images, tables, etc. In RichTextBox,
you are allowed to change the foreground color of the RichTextBox control using ForeColor Property
which makes your RichTextBox control more attractive.
9. DateTimePicker
10. TreeView
11. ListView
12. OpenFileDialog
13. ColorDialog
14. FontDialog
Homework 1: https://docs.microsoft.com/en-us/visualstudio/ide/tutorial-2-create-a-timed-math-
quiz?view=vs-2019
Homework 2: https://docs.microsoft.com/en-us/visualstudio/ide/tutorial-3-create-a-matching-
game?view=vs-2019
CHAPTER 18
References
1. https://www.computerhope.com/jargon/p/program.htm
2. https://hackr.io/blog/what-is-programming
3. https://dm7blog.wordpress.com/2011/07/09/programlama-ve-gorsel-programcilik-nedir/
4. https://www.techopedia.com/definition/22855/visual-programming-language-vpl
5. [https://www.donnfelker.com/how-did-c-get-its-name/]
6. https://www.educative.io/edpresso/what-is-c-used-for
7. https://steemit.com/writing/@adolp/best-programming-languages-to-learn-in-2018
8. https://trungtq.com/2019/02/06/why-learn-c/
9. Computer and Information Technology, Programming in Visual C# 2008,
Bradley−Millspaugh
10. C# ile Görsel Programlama-I Ders Notları, Dr. Bülent Çobanoğlu
11. https://docs.microsoft.com/tr-tr/dotnet/csharp/getting-started/introduction-to-the-csharp-
language-and-the-net-framework
12. https://docs.microsoft.com/en-us/visualstudio/get-started/csharp/visual-studio-ide?
view=vs-2019
13. https://www.c-sharpcorner.com/article/creating-console-application-in-c-sharp/
14. https://www.geeksforgeeks.org/introduction-to-c-sharp-windows-forms-applications/
#:~:text=Windows%20Forms%20is%20a%20Graphical,for%20desktop%2C%20tablet
%2C%20PCs.&text=WinForms%20applications%20can%20contain%20the,%2C%20list
%20boxes%2C%20tooltip%20etc.
15. http://net-informations.com/faq/net/dll.htm
16. https://www.programiz.com/csharp-programming/namespaces
17. https://docs.microsoft.com/tr-tr/dotnet/csharp/programming-guide/inside-a-program/hello-
world-your-first-program?tabs=windows
18. http://tecnokolik.com/visual-studio-2017-klavye-kisayol-tuslari-keyboard-shortcuts/
19. https://www.tutorialspoint.com/csharp/csharp_operators.htm
20. https://qawithexperts.com/tutorial/c-sharp/22/c-sharp-class-and-objects
21. https://www.tutorialsteacher.com/csharp/csharp-multi-dimensional-array
22. https://www.w3schools.com/cs/cs_classes.asp
23. http://csharp.net-informations.com/gui/cs_forms.htm
24. https://docs.microsoft.com/tr-tr/dotnet/api/system.windows.forms.form?view=netcore-3.1
25. https://www.geeksforgeeks.org/button-in-c-sharp/?ref=lbp