What is C# all about?
C# was developed at Microsoft. It is an object-oriented programming language and provides excellent features such as strong type checking, array bounds checking and automatic garbage collection. We will explore these and several other features in this article.
C# has features that make it an excellent choice for developing robust distributed n-tier Enterprise applications, web applications, windows applications and embedded systems. It is used for building applications ranging from the very large that use sophisticated operating systems, down to the very small having specialist functions
Getting Started:
Here is a very simple “Hello World” program written using C#. The code for C# program is written in text files with an extension “.cs”
Example:
1) Create a text file “First.cs”
2) Type the following code and ‘save’
using System;
class myClass
{
static void Main()
{
Console.WriteLine("Hello World");
}
}
3) From the command line compile the above code by typing the following
csc First.cs
4) This creates First.exe
5) Run this exe from the command line and you see an output –
Hello World
Having seen the example above we will now review the concepts and elements of the C# programming language. After that we will review the above example once again to understand what each line of code does. To get a better grasp of the C# language it is helpful if you have some programming experience and even better if you have experience in Object Oriented Programming. We now examine the C# language concepts and elements one by one.
A) OOP
C# is an object oriented Programming language and it supports the Object Oriented Programming Methodology. When creating a software solution you can represent the real world entities as “objects” of different “types”.
a. Types: C# supports mainly two kinds of types: value types and Reference types. The difference lies in the way in which handles these tow kinds of types. Examples of value types are – char, int, structures, enums . Examples of Reference types are – class, interface, delegate, arrays
i. Variables represent storage locations. Every variable is of a specific ‘type’. This determines what values can be stored in it.
ii. Field is a variable that is associated with a Class or Struct, or an instance of a class or struct.
iii. Parameters: There are four kinds of parameters: value parameters, reference parameters, output parameters, and parameter arrays.
iv. Classes: Classes are blueprints for objects. You instantiate an object from class. An object thus instantiated if said to be of a reference types. As C# is an Object Oriented Programming Language a class can inherit from another class, and can implement interfaces. Each Class can have one or members such as methods, properties, constants, fields, events, constructors, destructors and so on.
v. Structs: Structs are similar to classes in many ways. They have members and they can implement interfaces. They are fundamentally different from classes. STRUCTS are value types. STRUCT values are stored "on the stack" or "in-line". They cannot be inherited from any other class or reference type.
vi. Interfaces: What is an interface? An Interface simplifies a complex process by providing easy to use methods. Consider you need to change the channel on your TV or increase its volume, how do we do this, we use a Remote Control to change the channel or increase the volume. In this context, a Remote Control acts as an interface between you and your TV. Using a Remote Control one can perform required operation and control various functionality available in TV.
An interface defines a contract. When a class or a struct implements an interface with the help of methods and properties. A type (CLASS or STRUCT) that implements an interface must adhere to its contract. Interfaces can contain methods, properties, events, and indexers as members.
vii. Delegates: C# implements the functionality of function pointers using Delegates.
A delegate instance encapsulates a list of one or more methods, each of which is referred to as a callable entity. When a delegate instance is invoked it causes the delegate instance's callable entity to be invoked.
viii. Enums: An enum type declaration defines a type name for a related group of symbolic constants.
ix. Predefined types: The predefined value types include
signed integral types (sbyte, short, int, and long)
unsigned integral types (byte, ushort, uint, and ulong)
floating-point types (float and double)
bool
char
decimal
x. Nullable types These are constructed using the ‘?’ type modifier.
int? is the nullable form of the predefined type int.
int? x = 42;
int? z = null;
The nullable type is a structure. This structure has two members :
- A value of the underlying type (“Value”)
- A Boolean null indicator (“HasValue”)
HasValue is true for a non-null instance and false for a null instance. When HasValue is true, the Value property returns the contained value.
When HasValue is false, an attempt to access the Value property throws an exception.
if (x.HasValue) Console.WriteLine(x.Value);
An implicit conversion exists from any non-nullable value type to a nullable form of that type.
B) Namespaces
C# programs are organized using namespaces. Namespaces provide a hierarchical means of organizing the elements of one or more programs. They also provide a way of presenting program elements that are exposed to other programs. For instance in our example
namespace Company1.Dept2
{
class manager {}
class emp {}
}
namespace Company1
{
namespace Dept2
{
class manager {}
class emp {}
}
}
Namespaces are open-ended, and two namespace declarations with the same fully qualified name contribute to the same declaration space In the example
namespace Company1.Dept2
{
class manager {}
}
namespace Company1.Dept2
{
class emp {}
}
the two namespace declarations above contribute to the same declaration space,
Assemblies Assemblies are used for physical packaging and deployment. An assembly can contain the executable code and references to other assemblies.
C) Language Grammar
a. Expressions: An expression is a sequence of operands (variables, literals, etc) and operators An expression can be classified as one of the following:
value
variable
namespace
type
method group
property access
event access
indexer access
void or Nothing
The output of an expression can never be a namespace, type, method group, or
b. Statements: C# statements can be classified as one of the following:
labeled-statement
declaration-statement
embedded-statement
embedded-statement: (statements that appear within other statements)
empty-statement
expression-statement
selection-statement
iteration-statement
jump-statement
try-statement
checked-statement
unchecked-statement
lock-statement
using-statement
c. Constants: A constant is a class member that represents a constant value: a value that can be computed at compile-time. Constants can depend on other constants within the same program.
class myClass
{
public const int A = 1;
public const int B = A + 1;
}
d. Fields: A field is a member that represents a variable associated with an object or class.
e. Operators: The operators of an expression indicate which operations to apply to the operands. Examples of operators: +, -, *, /, new. There are three kinds of operators:
Unary operators. The unary operators take one operand and use either prefix notation (such as –-counter) or postfix notation (such as counter++).
Binary operators. The binary operators take two operands and all use infix notation (such as intA + intY).
Ternary operator. Only one ternary operator, ?:, exists; it takes three operands and uses infix notation (condition? intX: intY).
Certain operators can be overloaded. Operator overloading permits user-defined behavior for the operator.
f) Methods: A method is a member of the class. It implements functionality or behavior or action that can be performed by an instance of that class. Methods can have one or more formal parameters, an optional return value
g) Properties: A property is a member of the class. It provides access to a feature or characteristic of an instance of the class. In the example below: class car has a property CarColor
public class car
{
private string _CarColor;
public string CarColor
{
get
{
return _CarColor;
}
set
{
_CarColor = value;
}
}
}
h) Event: An event is also a member of the class. It enables an object or class to provide notifications when an event occurs. Example
public delegate void EventHandler(object sender, System.EventArgs e);
public class Button
{
public event EventHandler Click;
public void Reset() {
Click = null;
}
}
using System;
public class Form1
{
public Form1() {
Button1.Click += new EventHandler(doSomething);
}
Button Button1 = new Button();
void doSomething(object sender, EventArgs e) {
Console.WriteLine("Button1 was clicked and I did Something!");
}
public void Disconnect() {
Button1.Click -= new EventHandler(doSomething);
}
}
i) Comments: Two forms of comments are supported: delimited comments and single-line comments. A delimited comment begins with the characters /* and ends with the characters */. Delimited comments can occupy a portion of a line, a single line, or multiple lines. A single-line comment begins with the characters // and extends to the end of the line.
/* This is my First Program
This is where it gets started
*/
class myFirstProgram
{
static void Main() {
System.Console.WriteLine("Welcome Aboard!"); // Comment
}
}
j) Conditional Statements The if statement selects a statement for execution based on the value of a Boolean expression. Examples:
if ( boolean-expression ) embedded-statement
if ( boolean-expression ) embedded-statement else embedded-statement
if (x) if (y) F(); else G();
if (x)
{
if (y) {
F();
}
else {
G();
}
}
The switch statement : Based on the value of the switch expression. The switch statement matches a switch label and executes the statement(s) that corresponds to it
Example:
switch (iMatch) {
case 0:
Matched_Zero();
break;
case 1:
Matched_One();
break;
default:
Matched_None();
break;
}
k) Iteration statements : Iteration statements repeatedly execute an embedded statement.
Types of iteration statements:
while-statement
do-statement
for-statement
foreach-statement
Keywords in C#
l) Conversions A conversion enables an expression of one type to be treated as another type. Conversions can be implicit or explicit. A conversion enables an expression of one type to be treated as another type. Conversions can be implicit or explicit.
A conversion enables an expression of one type to be treated as another type. Conversions can be implicit or explicit.
m) Arrays An array is a data structure. It contains one or more variables that are accessed through computed indices. The elements of the array, are all of the same type.
n) Memory Management: One of the most important features of C# is automatic memory management implemented using a ‘garbage collector’. The process scans thru the objects created in the program and if the object can no longer be accessed the memory is cleared up
o) Indexers : An indexer enables an object to be indexed in the same way as an array.
Indexer declarations are similar to property declarations. The indexing parameters are provided between square brackets. Example
Visual Basic
Microsoft Visual Basic is a production environment used to create computer applications for the Microsoft Windows family of operating systems. The environment is fairly easy to use but you must know its "language". At its foundation, Microsoft Visual Basic uses a language that has been developed and improved over the years. It started with Basic but has had incremental flavors such as QuickBasic or QBasic.
Microsoft Visual Basic is used to create graphical applications, also referred to as Graphical User Interface (GUI) applications, web-based applications, and other types of applications. In order to effectively create these applications, you must be familiar with the language used in this programming environment. Most other programming environments use a known but separate language. For example, Microsoft Visual C++ 2005 uses many languages including C, C++, and C++/CLI. Borland Delphi uses the Object Pascal language, Microsoft Visual C# uses the C# language, Borland JBuilder uses the Java language. There is no official name for the language used by Microsoft Visual Basic. In our lessons, we will call the "Visual Basic Language".
In our lessons, we are going to study the language that serves as a foundation to the Microsoft Visual Basic programming environment.
Console Applications
As opposed to a GUI application, a console application is one that displays its results in a black window also called the DOS window. In our lessons, we will create only console applications. To follow these lessons, you must have an environment that allows you to create these types of applications using the Visual Basic language.
If you have already installed Microsoft Visual Studio 2008 Professional, you should be ready to follow these lessons. As an alternative, Microsoft created and made freely available Microsoft Visual Basic 2008 Express Edition. To get Microsoft Visual Basic 2008 Express Edition, you can access the MSDN section of the Microsoft web site and look for a link that displays Visual Studio Express Editions, then download Microsoft Visual Basic 2008 Express Edition. After downloading it, you must install and register it.
The Compiler
A computer program, also called a program, also called a computer application, also called an application, is a series of instructions that allows a person, called a user, to interact with the computer. This works by the user giving instructions to the machine. Such instructions can be done by performing actions such as clicking, typing, etc. To make this possible, a person like you, also called a program developer, or a developer, or an application developer, or a programmer, creates these instructions, decides what a particular application can do, what it cannot do, and what it should not do.
Once the application has been developed, it is then made available to users who must simply apply the instructions that a programmer created.
The programmer is the person who creates instructions that a user can apply on a computer application when interacting with the machine. The instructions are written in plain, easily understandable English, using normal computer files. Because the computer cannot understand them, the instructions are handed to an intermediary program that can "translate" them in a language the computer can understand. This intermediary application is called a compiler.
The Microsoft Visual Basic language includes a compiler named vbc. Like most other programs, it has the extension .exe. Therefore, it is called vbc.exe.
Console Program Creation
Introduction
To create a console application in Microsoft Visual Basic, after starting your programming environment:
If you are using Microsoft Visual Basic 2008 Express, on the main menu, you can click File -> New Project...
If you are using Microsoft Visual Studio 2008 Professional, on the main menu, you can click File -> New -> Project... In the Project Types list, click Visual Basic.
In both cases, in the Templates list, you will click Console Application. In the Name box, accept the suggested name or give a name of your choice:
When you are ready to create the project, click OK.
A Program's File
As mentioned already, when creating your programs, you will write text-based instructions in a file, also called a source file. A source file that contains Visual Basic instructions is a regular, simple, ASCII, text-based file. It has the extension .vb as a Windows file. To assist you with creating source files, Microsoft Visual Basic provides a dialog box.
Introduction to Modules
A program is started from a plain text file that has the .vb extension. In this file, you write code as we will learn throughout our lessons. The code that is conform to the Visual Basic language is included in a section known as the module. This section starts with the Module keyword followed by a name and ends with the End Module expression. Everything between the Module keyword and the End Module expression belong to the same entity. Based on this, a simple file in Visual Basic would have the following:
Module ModuleName
End Module
To create a source file, on the main menu, you can click Project -> Add Module, or Project -> Add New Item. In the Add New Item dialog box, make sure Module is selected or click it. In the Name text box, accept the suggested name or change it. Then click Add.
Introduction to Procedures
A procedure is a section of code that takes care of a specific task. In a module, the basic formula of a procedure is:
Sub ProcedureName()
End Sub
Notice that it ends with the End Sub line. Because a module holds the code of a Visual Basic program, a procedure is included inside the start and the end of the module section. This would be done as follows:
Module ModuleName
Sub ProcedureName()
End Sub
End Module
We will come back to procedures in another lesson. For now, the most fundamental procedure used in Visual Basic is called Main. In a program, the Main procedure is the entry point. That is where the program starts. When you create a console application using the New Project dialog box, sample code would be written for you and it would include the Main procedure that would appear as follows:
Module Module1
Sub Main()
End Sub
End Module
Another common procedure highly used in Visual Basic is called MsgBox. As its name indicates, the MsgBox procedure is used to display a message in a dialog box. To make this happen, you can include the message inside the parentheses of MsgBox. The message itself should be included in double-quotes. An example would be:
MsgBox("Whatever")
To distinguish a procedure from other items used in a program, we will sometimes write it followed by parentheses. Examples are Main() and MsgBox().
The MsgBox() procedure provides more details. We will come back to it in Lesson 7.
Practical Learning: Introducing the Visual Basic Language
Start Microsoft Visual Basic (2008 Professional or 2008 Express Edition)
To create a new application, on the main menu, click File -> New -> Project... (or File -> New Project...)
In the Project Types list, make sure Visual Basic is selected.
In the Templates list, click Console Application
Set the Name to Exercise
Click OK
To use the MsgBox procedure, change the file as follows:
Module Module1
Sub Main()
MsgBox("This is the wonderful world of VBasic")
End Sub
End Module
To execute the application, on the main menu, click Debug -> Start Without Debugging
After seeing the result, click OK on the message box
Press Enter to close the DOS window
A Solution and its Projects
A Solution
Throughout our lessons, we will learn how to create (console) applications. These are created from a project. So far, we have been able to create a project. In reality, such a project is created inside of another ensemble referred to as a solution. A solution is automatically created for you when you start a new project. We will learn that you can add as many projects as you want, to a solution.
When you start a new application from the New Project dialog box, you are asked whether you want to create a new solution too, and you must give it a name. By default, the new project and solution would hold the same name. If you accept the suggestions, you would get a main folder with the name of the project. Inside of that folder, there would be a folder with the same name. That inside folder would represent the project.
After creating a solution, its name appears on the title bar of Microsoft Visual Studio. The name of the project would appear in the Solution Explorer.
Practical Learning: Creating a Solution
To start a new project with its solution, on the main menu, click File -> New -> Project (or File -> New Project)
In the Templates list, click Console Application
In the Name Text box, type StudentsRecords
In the Solution Name, type SchoolManagement
Click OK
Notice the name of the solution on the title bar and the name of the project in the Solution Explorer
Click under the Sub Main() line and type msgbox("First Project")
Working on Additional Projects
So far, we were working on a solution with a single project. In some cases, you may want to work on various projects. Instead of always creating a new project, you can add a new project to a solution you are working on.
To add a new project to a solution, on the main menu, click File -> Add -> New Project... This would display the Add New Project dialog box. In the Templates list, select the type of project you want. Accept or change the name of the project, then click OK.
The names of the different projects are listed in the Solution Explorer.
Practical Learning: Adding a Solution
To add a new project to the current solution, on the main menu, click File -> Add -> New Project
In the Add New Project dialog box, click Console Application
In the Name Text box, type FinancesAndAccounting
Click OK
A Project and its Files
Adding a File to a Project
In our projects so far, when we created a project, a default file was created for it. If necessary, you can add as many files as necessary to a project. To add a file to a project:
On the main menu, you can click Project -> Add New Item...
In the Solution Explorer, you can right-click the name of the project, position the mouse on Add, and click New Project...
This would display the Add New Item dialog box with the name of the project on the title bar. In the Templates list, you can select the type of file you want to create, give it a name, and click Add or press Enter.
Opening a File
Once a file has been added to a project, you can use it. Some operations require that the file be opened. To open a file, in the Solution Explorer, under the name of the project:
Double-click the file
Right-click the file and click Open
On the main menu, click File -> Open -> File... Locate the folder of the project. In most cases, the file would be located in the Debug folder inside the bin folder of the project. After locating and selecting the file, click it and click Open
Renaming a File
In the introduction we have had so far, we learned to create a small console projects with one file. That first file was named Module1. Because this name can be too generic or vague, you can change it at any time.
To rename a file, in the Solution Explorer, under the name of the project that holds the file, right-click it and click Rename. Then type a name with the .vb extension and press Enter.
Practical Learning: Renaming a File
In the Solution Explorer, under StudentsRecords, right-click Module1.vb and click Rename
Type Registrations and press Enter
Still in the Solution Explorer, under FinancesAndAccount, right-click Module1.vb and click Rename
Type Payroll and press Enter
In the Solution Explorer, click StudentsRecords to select it
On the main menu, click Debug -> Start Without Debugging
In the Solution Explorer, under FinancesAndServices, double-click Payroll and
Adding an External File
When working on a project, if there is a file in another project and you want to use that file in your project, you can import that file. To do this;
On the main menu, you can click Project -> Add Existing Item...
In the Solution Explorer, you can right-click the name of the project to which you want to import the file, position the mouse on Add, and click Existing Item...
Any of these actions would display the Add Existing Item dialog box with the name of the project on the title bar. Locate the file, select it, and click Open.
Removing a File From a Project
If you have a file in a project but do not need that file anymore, you can delete it. To remove a file, in the Solution Explorer, under the project, right-click the name of the file and click Delete.
Accessories for Code Writing
Comments
A comment is text that the compiler does not process when reading your code. As such, a comment can be written any way you want. In the Visual Basic language, the line that contains a comment can start with a single quote. Here is an example:
Module Module1
Sub Main()
' This line will not be considered as part of the code
End Sub
End Module
Alternatively, you can start a comment with the Rem keyword. Anything on the right side of rem, Rem, or REM would not be processed. Here is an example:
Module Module1
Sub Main()
' This line will not be considered as part of the code
Rem I can write anything I want on this line
End Sub
End Module
Comments are very useful and you are strongly suggested to use comments regularly. They can never hurt your code and they do not increase the size of your application. Comments can help you and other people who read your code to figure out what a particular section of code is used for, which can be helpful when you re-visit your code after months or years of not seeing it.
White Spaces
When writing code, you will have to separate different parts with spaces, like the one between Sub and Main. This is referred to as white space. The amount of space you put between two words is not important. The compiler would ignore the white spaces between words. This means that Sub Main() and Sub Main() would the same effect. In the same way
Sub Main()
and
Sub Main()
would produce the same effect.
Microsoft Visual Basic is used to create graphical applications, also referred to as Graphical User Interface (GUI) applications, web-based applications, and other types of applications. In order to effectively create these applications, you must be familiar with the language used in this programming environment. Most other programming environments use a known but separate language. For example, Microsoft Visual C++ 2005 uses many languages including C, C++, and C++/CLI. Borland Delphi uses the Object Pascal language, Microsoft Visual C# uses the C# language, Borland JBuilder uses the Java language. There is no official name for the language used by Microsoft Visual Basic. In our lessons, we will call the "Visual Basic Language".
In our lessons, we are going to study the language that serves as a foundation to the Microsoft Visual Basic programming environment.
Console Applications
As opposed to a GUI application, a console application is one that displays its results in a black window also called the DOS window. In our lessons, we will create only console applications. To follow these lessons, you must have an environment that allows you to create these types of applications using the Visual Basic language.
If you have already installed Microsoft Visual Studio 2008 Professional, you should be ready to follow these lessons. As an alternative, Microsoft created and made freely available Microsoft Visual Basic 2008 Express Edition. To get Microsoft Visual Basic 2008 Express Edition, you can access the MSDN section of the Microsoft web site and look for a link that displays Visual Studio Express Editions, then download Microsoft Visual Basic 2008 Express Edition. After downloading it, you must install and register it.
The Compiler
A computer program, also called a program, also called a computer application, also called an application, is a series of instructions that allows a person, called a user, to interact with the computer. This works by the user giving instructions to the machine. Such instructions can be done by performing actions such as clicking, typing, etc. To make this possible, a person like you, also called a program developer, or a developer, or an application developer, or a programmer, creates these instructions, decides what a particular application can do, what it cannot do, and what it should not do.
Once the application has been developed, it is then made available to users who must simply apply the instructions that a programmer created.
The programmer is the person who creates instructions that a user can apply on a computer application when interacting with the machine. The instructions are written in plain, easily understandable English, using normal computer files. Because the computer cannot understand them, the instructions are handed to an intermediary program that can "translate" them in a language the computer can understand. This intermediary application is called a compiler.
The Microsoft Visual Basic language includes a compiler named vbc. Like most other programs, it has the extension .exe. Therefore, it is called vbc.exe.
Console Program Creation
Introduction
To create a console application in Microsoft Visual Basic, after starting your programming environment:
If you are using Microsoft Visual Basic 2008 Express, on the main menu, you can click File -> New Project...
If you are using Microsoft Visual Studio 2008 Professional, on the main menu, you can click File -> New -> Project... In the Project Types list, click Visual Basic.
In both cases, in the Templates list, you will click Console Application. In the Name box, accept the suggested name or give a name of your choice:
When you are ready to create the project, click OK.
A Program's File
As mentioned already, when creating your programs, you will write text-based instructions in a file, also called a source file. A source file that contains Visual Basic instructions is a regular, simple, ASCII, text-based file. It has the extension .vb as a Windows file. To assist you with creating source files, Microsoft Visual Basic provides a dialog box.
Introduction to Modules
A program is started from a plain text file that has the .vb extension. In this file, you write code as we will learn throughout our lessons. The code that is conform to the Visual Basic language is included in a section known as the module. This section starts with the Module keyword followed by a name and ends with the End Module expression. Everything between the Module keyword and the End Module expression belong to the same entity. Based on this, a simple file in Visual Basic would have the following:
Module ModuleName
End Module
To create a source file, on the main menu, you can click Project -> Add Module, or Project -> Add New Item. In the Add New Item dialog box, make sure Module is selected or click it. In the Name text box, accept the suggested name or change it. Then click Add.
Introduction to Procedures
A procedure is a section of code that takes care of a specific task. In a module, the basic formula of a procedure is:
Sub ProcedureName()
End Sub
Notice that it ends with the End Sub line. Because a module holds the code of a Visual Basic program, a procedure is included inside the start and the end of the module section. This would be done as follows:
Module ModuleName
Sub ProcedureName()
End Sub
End Module
We will come back to procedures in another lesson. For now, the most fundamental procedure used in Visual Basic is called Main. In a program, the Main procedure is the entry point. That is where the program starts. When you create a console application using the New Project dialog box, sample code would be written for you and it would include the Main procedure that would appear as follows:
Module Module1
Sub Main()
End Sub
End Module
Another common procedure highly used in Visual Basic is called MsgBox. As its name indicates, the MsgBox procedure is used to display a message in a dialog box. To make this happen, you can include the message inside the parentheses of MsgBox. The message itself should be included in double-quotes. An example would be:
MsgBox("Whatever")
To distinguish a procedure from other items used in a program, we will sometimes write it followed by parentheses. Examples are Main() and MsgBox().
The MsgBox() procedure provides more details. We will come back to it in Lesson 7.
Practical Learning: Introducing the Visual Basic Language
Start Microsoft Visual Basic (2008 Professional or 2008 Express Edition)
To create a new application, on the main menu, click File -> New -> Project... (or File -> New Project...)
In the Project Types list, make sure Visual Basic is selected.
In the Templates list, click Console Application
Set the Name to Exercise
Click OK
To use the MsgBox procedure, change the file as follows:
Module Module1
Sub Main()
MsgBox("This is the wonderful world of VBasic")
End Sub
End Module
To execute the application, on the main menu, click Debug -> Start Without Debugging
After seeing the result, click OK on the message box
Press Enter to close the DOS window
A Solution and its Projects
A Solution
Throughout our lessons, we will learn how to create (console) applications. These are created from a project. So far, we have been able to create a project. In reality, such a project is created inside of another ensemble referred to as a solution. A solution is automatically created for you when you start a new project. We will learn that you can add as many projects as you want, to a solution.
When you start a new application from the New Project dialog box, you are asked whether you want to create a new solution too, and you must give it a name. By default, the new project and solution would hold the same name. If you accept the suggestions, you would get a main folder with the name of the project. Inside of that folder, there would be a folder with the same name. That inside folder would represent the project.
After creating a solution, its name appears on the title bar of Microsoft Visual Studio. The name of the project would appear in the Solution Explorer.
Practical Learning: Creating a Solution
To start a new project with its solution, on the main menu, click File -> New -> Project (or File -> New Project)
In the Templates list, click Console Application
In the Name Text box, type StudentsRecords
In the Solution Name, type SchoolManagement
Click OK
Notice the name of the solution on the title bar and the name of the project in the Solution Explorer
Click under the Sub Main() line and type msgbox("First Project")
Working on Additional Projects
So far, we were working on a solution with a single project. In some cases, you may want to work on various projects. Instead of always creating a new project, you can add a new project to a solution you are working on.
To add a new project to a solution, on the main menu, click File -> Add -> New Project... This would display the Add New Project dialog box. In the Templates list, select the type of project you want. Accept or change the name of the project, then click OK.
The names of the different projects are listed in the Solution Explorer.
Practical Learning: Adding a Solution
To add a new project to the current solution, on the main menu, click File -> Add -> New Project
In the Add New Project dialog box, click Console Application
In the Name Text box, type FinancesAndAccounting
Click OK
A Project and its Files
Adding a File to a Project
In our projects so far, when we created a project, a default file was created for it. If necessary, you can add as many files as necessary to a project. To add a file to a project:
On the main menu, you can click Project -> Add New Item...
In the Solution Explorer, you can right-click the name of the project, position the mouse on Add, and click New Project...
This would display the Add New Item dialog box with the name of the project on the title bar. In the Templates list, you can select the type of file you want to create, give it a name, and click Add or press Enter.
Opening a File
Once a file has been added to a project, you can use it. Some operations require that the file be opened. To open a file, in the Solution Explorer, under the name of the project:
Double-click the file
Right-click the file and click Open
On the main menu, click File -> Open -> File... Locate the folder of the project. In most cases, the file would be located in the Debug folder inside the bin folder of the project. After locating and selecting the file, click it and click Open
Renaming a File
In the introduction we have had so far, we learned to create a small console projects with one file. That first file was named Module1. Because this name can be too generic or vague, you can change it at any time.
To rename a file, in the Solution Explorer, under the name of the project that holds the file, right-click it and click Rename. Then type a name with the .vb extension and press Enter.
Practical Learning: Renaming a File
In the Solution Explorer, under StudentsRecords, right-click Module1.vb and click Rename
Type Registrations and press Enter
Still in the Solution Explorer, under FinancesAndAccount, right-click Module1.vb and click Rename
Type Payroll and press Enter
In the Solution Explorer, click StudentsRecords to select it
On the main menu, click Debug -> Start Without Debugging
In the Solution Explorer, under FinancesAndServices, double-click Payroll and
Adding an External File
When working on a project, if there is a file in another project and you want to use that file in your project, you can import that file. To do this;
On the main menu, you can click Project -> Add Existing Item...
In the Solution Explorer, you can right-click the name of the project to which you want to import the file, position the mouse on Add, and click Existing Item...
Any of these actions would display the Add Existing Item dialog box with the name of the project on the title bar. Locate the file, select it, and click Open.
Removing a File From a Project
If you have a file in a project but do not need that file anymore, you can delete it. To remove a file, in the Solution Explorer, under the project, right-click the name of the file and click Delete.
Accessories for Code Writing
Comments
A comment is text that the compiler does not process when reading your code. As such, a comment can be written any way you want. In the Visual Basic language, the line that contains a comment can start with a single quote. Here is an example:
Module Module1
Sub Main()
' This line will not be considered as part of the code
End Sub
End Module
Alternatively, you can start a comment with the Rem keyword. Anything on the right side of rem, Rem, or REM would not be processed. Here is an example:
Module Module1
Sub Main()
' This line will not be considered as part of the code
Rem I can write anything I want on this line
End Sub
End Module
Comments are very useful and you are strongly suggested to use comments regularly. They can never hurt your code and they do not increase the size of your application. Comments can help you and other people who read your code to figure out what a particular section of code is used for, which can be helpful when you re-visit your code after months or years of not seeing it.
White Spaces
When writing code, you will have to separate different parts with spaces, like the one between Sub and Main. This is referred to as white space. The amount of space you put between two words is not important. The compiler would ignore the white spaces between words. This means that Sub Main() and Sub Main() would the same effect. In the same way
Sub Main()
and
Sub Main()
would produce the same effect.
C++ Language Basics
C++ Language Basics Part I
(I/O, functions, keywords, structures, memory alloc, commenting)
The C++ programming language can be thought of as a ``superset'' of the C language; that is, just about any legal Ansi C program is a legal C++ program, and means the same thing. The reverse is not true of course: there are many C++ constructs that are not found in the C programming language. This handout describes some of those constructs that we will be using in this class.
Input and Output
In C, input and output is traditionally done using the functions printf and scanf (along with getchar()). When reading from files, the routines fprintf and fscanf are used. Unfortunately, it's pretty easy to crash a program using these functions. For example,
int d = 3;
char *str = "hi there!";
printf("d is %d, and str is %s\n", str, d);
will probably cause your program to crash, because the programmer mixed up the arguments to printf. The routine scanf is even worse: for example,
double d;
float f;
int i;
scanf("%d", i); /* wrong, should be &i */
scanf("%f", &d); /* wrong, needed to specify %lf */
scanf("%f", &f); /* this one is OK */
The major problem is that you can usually only find these bugs at run-time. However, it would be much better for the compiler to be able to look at the statement scanf("%d", i) and determine that a pointer to an integer, not simply an integer, was required here. While you can't do that with C style operators (since the correct arguments to printf and scanf vary, depending on the formatting string), in C++ there are routines that will eliminate most of these bugs.
Let's look at an example:
#include
main() {
int a, b;
double d;
char str[20];
cin >> a; // equivalent to scanf("%d", &a);
cin >> b; // equivalent to scanf("%d", &b);
cin >> d; // equivalent to scanf("%lf", &d);
cin >> str; // equivalent to scanf("%s", str);
cout << "The sum of a and b is"; cout << a + b; cout << "\n"; } First, the file iostream.h is a standard C++ header file that defines cin, cout, and the operators << and >>. The expression cin >> a causes the program to read an integer into the variable a, from the standard input. Similarly, cin >> b reads an integer into b, but cin >> d interprets its input as a real number, and stores it in d. The next statement, cin >> str reads characters until a whitespace is encountered, and stores a null-terminated string in str (excluding the whitespace). Note that if you typed a very long string (i.e. more than 20 characters), your program could crash.
Output is much the same: with the expression cout << thing, the contents of thing is printed to the standard output. Note a couple of subtleties: int ival = 'g'; // The ASCII code for g is 103, so ival = 'g' char cval = 'g'; // is equivalent to ival = 103. cout << ival; // treats ival as a number, and prints out 103 cout << cval; // prints out simply the letter g A few other things: You can combine any number of output or input operations in a row e.g. cin >> a >> b >> d >> str;
is fine, and is equivalent to the four seperate lines above. Similarly, statements like
cout << "The sum of a and b is " << a+b << "\n"; are permissible as well. (Note the space after the word ``is.'' Without extra space, i.e., int x = 23; cout << "The value of x is" << x << "\n"; you get The value of x is23 You can test when you've run out of input: int x; while(cin >> x) {
...
}
will loop until there is no more input, or until an invalid string is entered (e.g. ``hi,'' which is not a valid integer).
It is also possible to make the << and >> output operators know how to output user-defined types: for example, if you create new datatypes, you can teach the << and >> operators how to input and output directly from those datatypes. (See the C++ book, or ask the teaching staff how this works, if you're interested).
If you want to do I/O to a file (i.e. the equivalent of fprintf), you can get declare variables like cout that are used just as cout is, but that cause the output to go to a particular file. You can do input from a file similarly. There is an example of this in Assignment 1. If you want to know more details, consult the C++ book, or the teaching staff.
Finally, in addition to sending output to cout, you can also send output to the ``standard error'' by using cerr e.g.
if(i < 0) { cerr << "Fatal error: i is less than zero!\n"; exit(1); } This is analogous to using fprintf to stderr. Function Declarations In C++ it is illegal to use a function without first declaring its type. In C, if you don't declare a function's type, certain defaults apply. This is not the case with C++. You must define a function before you can use it. Additional Keywords Every keyword, or reserved-word in C is also a keyword in C++. There are extra keywords in C++ that have no meaning in C. Since C++ is becoming prevalent, even when programming in C you should avoid the use of all of the following C++ keywords as function or variable names. In C++ you cannot use any of the following words as function or variable names: asm delete if return try auto do inline short typedef break double int signed union case else long sizeof unsigned catch enum new static virtual char extern operator struct void class float private switch volatile const for protected template while continue friend public this default goto register throw Defining Structures In C++, when you define a structure, the name of the structure is henceforth treated as a new datatype. For example: struct complex { double x, y; }; complex a, b, c; Also, note the semicolon at the end of the definition of the complex structure: this semicolon is required. After defining the structure, you can use complex as a datatype. Its still legal to say struct complex a, b, c; if you want to. The above discussion applies to unions as well. Memory Allocation In C, we allocate space using malloc. For example, double *dspace = (double *)malloc(sizeof(double) * 10); dynamically allocates space for 10 doubles. In C++, we use the construct new: double *dspace = new double[10]; To allocate space for the complex structure defined above, the syntax is simply complex *cptr = new complex[37]; To return memory in C, we use free: free(dspace); In C++, memory is returned by delete dspace; /* or, delete []dspace; */ or delete cptr; /* or, delete []cptr; */ The format with square brackets is needed when you have an array of items each having its own destructor (we'll talk about destructors later on in the course). As in C, though, if you try to write past the end of the memory allocated by new, your program will probably not work correctly. Incidentally, the delete operator is guaranteed to have no effect when applied to a pointer whose value is zero (NULL). Handing delete a pointer that was not returned by new is a bad idea. To more easily catch cases when you've deleted memory but later tried to use it, the code delete dspace; dspace = 0; is recommended, since the use of dspace after the deletion will be easier to detect. Overloading of Functions In C, a name can only be used once to define a function. For example, in C, the following is illegal: double minimum(double x, double y) { if(x < y) return x; else return y; } int minimum(int x, int y) { if(x < y) return x; else return y; } This is perfectly legal C++ code, however, and is known as an overloaded function. If you call minimum in your code, the compiler will decide which version of minimum to invoke based on the types of the arguments you supply to the function. Appropriate uses for overloading are reusing mathematical function names for operations on different data; for example, two versions of sqrt: one for real numbers, and one for complex numbers. Another typical use might be a function named node_count which returns the number of nodes in differing data structures such as linked lists, trees, or graphs. You will probably have little use for operator overloading in this class. The reason we bring up the subject at all, is to make you aware of the following pitfall. Suppose that you declare in a header file defs.h a function foo as follows: /* file defs.h */ int foo(double, int, char); Now suppose that you wish to use the function foo in a file a.c: /* file a.c */ #include "defs.h" void do_something() { int result; result = foo(3.4, 7, 'c'); } Ok, no problems so far: the file a.c correctly includes defs.h so it can access the function foo. Suppose, though, you made a mistake in the file b.c, where foo is actually defined: /* file b.c */ #include "defs.h" /* Here's my great implementation of foo: by juxtaposing the seventh and ninth bit from the third argument, I cleverly manage to ... */ int foo(double a, int b, int c) { ... } The problem is that the C++ compiler thinks you're defining a function foo which takes a double and two integers. This is perfectly legal. The problem comes when you actually compile and try to run everything. At that point, the function named foo that takes a double, an integer, and a character, will be undefined, because in b.c you defined a different function foo. Moral of the story: if you get undefined function errors from the compiler, make certain that you defined your function with the types you really meant to. Commenting C++ allows two types of comments. In addition to the standard ``/*'' and ``*/'' comments of C, there is a special comment which is good only to the end of a line. In C++, characters occuring after the sequence ``//'' and on the same line are ignored, as long as the ``//'' does not occur in a string. For example: /* If low is greater than high, interchange the values and set 'swapped' to 1. */ if(low > high)
{
tmp = low; // save low
low = high;
high = tmp; // now swap
swapped = 1; // indicate we swapped the data
}
One thing to be VERY careful of is not to use C++ style comments in #define statements, because most compiler systems don't mix the two together correctly. That is, for now (and probably for at least another 10 years!) don't write
#define MAX_LEN 128 // maximum length string
but use
#define MAX_LEN 128 /* maximum length string */
instead.
(I/O, functions, keywords, structures, memory alloc, commenting)
The C++ programming language can be thought of as a ``superset'' of the C language; that is, just about any legal Ansi C program is a legal C++ program, and means the same thing. The reverse is not true of course: there are many C++ constructs that are not found in the C programming language. This handout describes some of those constructs that we will be using in this class.
Input and Output
In C, input and output is traditionally done using the functions printf and scanf (along with getchar()). When reading from files, the routines fprintf and fscanf are used. Unfortunately, it's pretty easy to crash a program using these functions. For example,
int d = 3;
char *str = "hi there!";
printf("d is %d, and str is %s\n", str, d);
will probably cause your program to crash, because the programmer mixed up the arguments to printf. The routine scanf is even worse: for example,
double d;
float f;
int i;
scanf("%d", i); /* wrong, should be &i */
scanf("%f", &d); /* wrong, needed to specify %lf */
scanf("%f", &f); /* this one is OK */
The major problem is that you can usually only find these bugs at run-time. However, it would be much better for the compiler to be able to look at the statement scanf("%d", i) and determine that a pointer to an integer, not simply an integer, was required here. While you can't do that with C style operators (since the correct arguments to printf and scanf vary, depending on the formatting string), in C++ there are routines that will eliminate most of these bugs.
Let's look at an example:
#include
main() {
int a, b;
double d;
char str[20];
cin >> a; // equivalent to scanf("%d", &a);
cin >> b; // equivalent to scanf("%d", &b);
cin >> d; // equivalent to scanf("%lf", &d);
cin >> str; // equivalent to scanf("%s", str);
cout << "The sum of a and b is"; cout << a + b; cout << "\n"; } First, the file iostream.h is a standard C++ header file that defines cin, cout, and the operators << and >>. The expression cin >> a causes the program to read an integer into the variable a, from the standard input. Similarly, cin >> b reads an integer into b, but cin >> d interprets its input as a real number, and stores it in d. The next statement, cin >> str reads characters until a whitespace is encountered, and stores a null-terminated string in str (excluding the whitespace). Note that if you typed a very long string (i.e. more than 20 characters), your program could crash.
Output is much the same: with the expression cout << thing, the contents of thing is printed to the standard output. Note a couple of subtleties: int ival = 'g'; // The ASCII code for g is 103, so ival = 'g' char cval = 'g'; // is equivalent to ival = 103. cout << ival; // treats ival as a number, and prints out 103 cout << cval; // prints out simply the letter g A few other things: You can combine any number of output or input operations in a row e.g. cin >> a >> b >> d >> str;
is fine, and is equivalent to the four seperate lines above. Similarly, statements like
cout << "The sum of a and b is " << a+b << "\n"; are permissible as well. (Note the space after the word ``is.'' Without extra space, i.e., int x = 23; cout << "The value of x is" << x << "\n"; you get The value of x is23 You can test when you've run out of input: int x; while(cin >> x) {
...
}
will loop until there is no more input, or until an invalid string is entered (e.g. ``hi,'' which is not a valid integer).
It is also possible to make the << and >> output operators know how to output user-defined types: for example, if you create new datatypes, you can teach the << and >> operators how to input and output directly from those datatypes. (See the C++ book, or ask the teaching staff how this works, if you're interested).
If you want to do I/O to a file (i.e. the equivalent of fprintf), you can get declare variables like cout that are used just as cout is, but that cause the output to go to a particular file. You can do input from a file similarly. There is an example of this in Assignment 1. If you want to know more details, consult the C++ book, or the teaching staff.
Finally, in addition to sending output to cout, you can also send output to the ``standard error'' by using cerr e.g.
if(i < 0) { cerr << "Fatal error: i is less than zero!\n"; exit(1); } This is analogous to using fprintf to stderr. Function Declarations In C++ it is illegal to use a function without first declaring its type. In C, if you don't declare a function's type, certain defaults apply. This is not the case with C++. You must define a function before you can use it. Additional Keywords Every keyword, or reserved-word in C is also a keyword in C++. There are extra keywords in C++ that have no meaning in C. Since C++ is becoming prevalent, even when programming in C you should avoid the use of all of the following C++ keywords as function or variable names. In C++ you cannot use any of the following words as function or variable names: asm delete if return try auto do inline short typedef break double int signed union case else long sizeof unsigned catch enum new static virtual char extern operator struct void class float private switch volatile const for protected template while continue friend public this default goto register throw Defining Structures In C++, when you define a structure, the name of the structure is henceforth treated as a new datatype. For example: struct complex { double x, y; }; complex a, b, c; Also, note the semicolon at the end of the definition of the complex structure: this semicolon is required. After defining the structure, you can use complex as a datatype. Its still legal to say struct complex a, b, c; if you want to. The above discussion applies to unions as well. Memory Allocation In C, we allocate space using malloc. For example, double *dspace = (double *)malloc(sizeof(double) * 10); dynamically allocates space for 10 doubles. In C++, we use the construct new: double *dspace = new double[10]; To allocate space for the complex structure defined above, the syntax is simply complex *cptr = new complex[37]; To return memory in C, we use free: free(dspace); In C++, memory is returned by delete dspace; /* or, delete []dspace; */ or delete cptr; /* or, delete []cptr; */ The format with square brackets is needed when you have an array of items each having its own destructor (we'll talk about destructors later on in the course). As in C, though, if you try to write past the end of the memory allocated by new, your program will probably not work correctly. Incidentally, the delete operator is guaranteed to have no effect when applied to a pointer whose value is zero (NULL). Handing delete a pointer that was not returned by new is a bad idea. To more easily catch cases when you've deleted memory but later tried to use it, the code delete dspace; dspace = 0; is recommended, since the use of dspace after the deletion will be easier to detect. Overloading of Functions In C, a name can only be used once to define a function. For example, in C, the following is illegal: double minimum(double x, double y) { if(x < y) return x; else return y; } int minimum(int x, int y) { if(x < y) return x; else return y; } This is perfectly legal C++ code, however, and is known as an overloaded function. If you call minimum in your code, the compiler will decide which version of minimum to invoke based on the types of the arguments you supply to the function. Appropriate uses for overloading are reusing mathematical function names for operations on different data; for example, two versions of sqrt: one for real numbers, and one for complex numbers. Another typical use might be a function named node_count which returns the number of nodes in differing data structures such as linked lists, trees, or graphs. You will probably have little use for operator overloading in this class. The reason we bring up the subject at all, is to make you aware of the following pitfall. Suppose that you declare in a header file defs.h a function foo as follows: /* file defs.h */ int foo(double, int, char); Now suppose that you wish to use the function foo in a file a.c: /* file a.c */ #include "defs.h" void do_something() { int result; result = foo(3.4, 7, 'c'); } Ok, no problems so far: the file a.c correctly includes defs.h so it can access the function foo. Suppose, though, you made a mistake in the file b.c, where foo is actually defined: /* file b.c */ #include "defs.h" /* Here's my great implementation of foo: by juxtaposing the seventh and ninth bit from the third argument, I cleverly manage to ... */ int foo(double a, int b, int c) { ... } The problem is that the C++ compiler thinks you're defining a function foo which takes a double and two integers. This is perfectly legal. The problem comes when you actually compile and try to run everything. At that point, the function named foo that takes a double, an integer, and a character, will be undefined, because in b.c you defined a different function foo. Moral of the story: if you get undefined function errors from the compiler, make certain that you defined your function with the types you really meant to. Commenting C++ allows two types of comments. In addition to the standard ``/*'' and ``*/'' comments of C, there is a special comment which is good only to the end of a line. In C++, characters occuring after the sequence ``//'' and on the same line are ignored, as long as the ``//'' does not occur in a string. For example: /* If low is greater than high, interchange the values and set 'swapped' to 1. */ if(low > high)
{
tmp = low; // save low
low = high;
high = tmp; // now swap
swapped = 1; // indicate we swapped the data
}
One thing to be VERY careful of is not to use C++ style comments in #define statements, because most compiler systems don't mix the two together correctly. That is, for now (and probably for at least another 10 years!) don't write
#define MAX_LEN 128 // maximum length string
but use
#define MAX_LEN 128 /* maximum length string */
instead.
Subscribe to:
Posts (Atom)