When a software developer mentiones the word "scope" the develeoper is refering to "What can see this object, how can it see it, and whats its access and relation to other objects", this may sound daunting but i can assure you, its easy stuff :)
When a variable is declared where all of a class's members can view it, it is called a "Global" variable.
So far in my previous examples we have declared variables inside a method and used
it in that method. This is called a "Local"object. This means that only the method that declared it can view and use/edit the data. If i were to declare a variable called "myvar" in method Main then tried to assign it a value in a method called "MethodOne", it would show an error because it is trying to access a variable out side of its scope, as that variables scope is inside the main method.
If we declared that variable inside the "class" then we can view it in all methods that are inside the "scope" of that class.
You cannot declare or make a statement insid ethe namespace, as the namespace is just to prevent Class name clashing!
Well thats all for this tutorial, i cant explain much more as we havent covered other C# principles, but there will be a part two to it so stay tuned!
Friday 31 July 2009
Beginning C# Lesson 3 - Variables
A variable is something that stores data.
It could be a character, number, image or many other things,
the thing you have to understand is how to declare and user
them, and what datatypes store which type fo data.
Variables are given a unique name inside the "scope" of the
program, i will talk about scope soon for now just understand that
we cant have two variables the same name in a method unless
the scope of the method changes.
Software developers can have long discussions on what datatypes
to use in a program, as using the wrong type could have negative
impact on your applications performance or maintability.
You dont neeed to know all of them at the moment but there are a few i will introduce you too:
Characters are two bytes in memory space, and are are assigned using 'charvalue' instead of the string "stringvalue", characters can hold a single character mfor example :
char myCharacter = 'M';
Example:
You can "Concatenate"(join) values inside a string. The Console.WriteLine(string) stores only a string, when you input arguments it trys to convert the data (if its not a string datatype) to string, using the "+" operator we can concatenate the string "My character is " with the variable myCharacter to form one string inside the writeline, when the WriteLine() has converted the values it will write it on the console.
Using "string"
string is a group or collection of characters concatenated to form a variable and its file size is two bytes per character.
We assign a value to a string datatype using quotations "stringvalue" for example:
string myString = "Strings are awesome";
string program example:
As you can see, we can join strings together too.
Using an Integer
Integer's are whole numbers (see the range from table) and is 3 bytes in memory.
They do not require quotations or apostrophe's and are assigned (as most numerical datatypes are) purely for example:
int myInteger = 100;
Because int only accepts whole numbers, we can not use decimal points.
Integer example:
Integers can also perform mathmatical operations known as "operators", operators work with raw data so when you see 2 + 2 your actually seeing:
0000 0010
0000 0010 +
Total = 0000 0100
Just like the concatenateoperator that joins the binary format of strings.
This is a big reason why we use datatypes, to tell the compiler how to computate
the binary representation. So "+" two strings or characters joins them and "+" two
integers adds them, there is some exceptions how ever, ie how would you join
the values of a string with an int?
The following code shows how:
Rerember a WriteLine(string) method accepts only string variables, and as previously
mentioned it attempts to convert its argument values to the string datatype.
The datatype int is one of those argument values that can be converted to a string with
little hassle, so when its used inside the WriteLine() method it is automaticly converted to a string, then the WriteLine() checks for any operators and finds "+", so its treats both variables as string and joins them together.
Also take note of the space i entered after "My int is", space is a character just like
all other characters on your keyboard, and is treated the same.
An example of math operators using ints:
Notice how I put the addition inside brackets?
Its because of the WriteLine() "Order of precedence", what operators are
checked and computated in order.
Brackets are higher order of precedence than joining the string, so it first calculates the
total of (a + b) then converts the result to a string and finally joins it to the string.
+ is addition.
* is multiplication.
/ is devide
% is modulas (remainder of a number)
Some other numerical datatypes such as "Decimal" (decimal) have the same operators and
work the same way.
Console input/output
Applications can take input and output, a Console application inherits those rules.
So far we have only outputted values using the Console.WriteLine() method from the Console class, how ever we can also input data into a variable!
An example, you need to store a persons first name , you could add this code inside your
Main method:
string name ;
Console.Write("Enter your first name : ");
name = Console.ReadLine();
Console.WriteLine("Your name is " + name);
Console.ReadKey();
The variable name is declared but not assigned a value,
then the console uses the "Write()" method.
The Write() method is similar to WriteLine() but instead of writing some text and then setting the cursor on a new line it just writes it on where ever the cursor is, please compile that code to understand visually!
Once the message is displayed, we use the Console.ReadLine() to read data from where ever the cursor was to the last character entered in the console.
You cannot explicity ReadLine() a datatype other than a string, to if you were to add data to
an int variable you would have to convert the ReadLine() data to an int which will be explained in another lesson.
That basicly sums up the introduction to variables lesson, hope it was fun :P
It could be a character, number, image or many other things,
the thing you have to understand is how to declare and user
them, and what datatypes store which type fo data.
Variables are given a unique name inside the "scope" of the
program, i will talk about scope soon for now just understand that
we cant have two variables the same name in a method unless
the scope of the method changes.
Software developers can have long discussions on what datatypes
to use in a program, as using the wrong type could have negative
impact on your applications performance or maintability.
Data Type | Range |
---|---|
byte | 0 .. 255 |
sbyte | -128 .. 127 |
short | -32,768 .. 32,767 |
ushort | 0 .. 65,535 |
int | -2,147,483,648 .. 2,147,483,647 |
uint | 0 .. 4,294,967,295 |
long | -9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807 |
ulong | 0 .. 18,446,744,073,709,551,615 |
float | -3.402823e38 .. 3.402823e38 |
double | -1.79769313486232e308 .. 1.79769313486232e308 |
decimal | -79228162514264337593543950335 .. 79228162514264337593543950335 |
char | A Unicode character. |
string | A string of Unicode characters. |
bool | True or False. |
object | An object. |
You dont neeed to know all of them at the moment but there are a few i will introduce you too:
- char - stores a single character
- string - stores a group of characters
- int - stores hole numbers (check the above table for its range)
Characters are two bytes in memory space, and are are assigned using 'charvalue' instead of the string "stringvalue", characters can hold a single character mfor example :
char myCharacter = 'M';
Example:
You can "Concatenate"(join) values inside a string. The Console.WriteLine(string) stores only a string, when you input arguments it trys to convert the data (if its not a string datatype) to string, using the "+" operator we can concatenate the string "My character is " with the variable myCharacter to form one string inside the writeline, when the WriteLine() has converted the values it will write it on the console.
Using "string"
string is a group or collection of characters concatenated to form a variable and its file size is two bytes per character.
We assign a value to a string datatype using quotations "stringvalue" for example:
string myString = "Strings are awesome";
string program example:
As you can see, we can join strings together too.
Using an Integer
Integer's are whole numbers (see the range from table) and is 3 bytes in memory.
They do not require quotations or apostrophe's and are assigned (as most numerical datatypes are) purely for example:
int myInteger = 100;
Because int only accepts whole numbers, we can not use decimal points.
Integer example:
Integers can also perform mathmatical operations known as "operators", operators work with raw data so when you see 2 + 2 your actually seeing:
0000 0010
0000 0010 +
Total = 0000 0100
Just like the concatenateoperator that joins the binary format of strings.
This is a big reason why we use datatypes, to tell the compiler how to computate
the binary representation. So "+" two strings or characters joins them and "+" two
integers adds them, there is some exceptions how ever, ie how would you join
the values of a string with an int?
The following code shows how:
Rerember a WriteLine(string) method accepts only string variables, and as previously
mentioned it attempts to convert its argument values to the string datatype.
The datatype int is one of those argument values that can be converted to a string with
little hassle, so when its used inside the WriteLine() method it is automaticly converted to a string, then the WriteLine() checks for any operators and finds "+", so its treats both variables as string and joins them together.
Also take note of the space i entered after "My int is", space is a character just like
all other characters on your keyboard, and is treated the same.
An example of math operators using ints:
Notice how I put the addition inside brackets?
Its because of the WriteLine() "Order of precedence", what operators are
checked and computated in order.
Brackets are higher order of precedence than joining the string, so it first calculates the
total of (a + b) then converts the result to a string and finally joins it to the string.
* is multiplication.
/ is devide
% is modulas (remainder of a number)
Some other numerical datatypes such as "Decimal" (decimal) have the same operators and
work the same way.
Console input/output
Applications can take input and output, a Console application inherits those rules.
So far we have only outputted values using the Console.WriteLine() method from the Console class, how ever we can also input data into a variable!
An example, you need to store a persons first name , you could add this code inside your
Main method:
string name ;
Console.Write("Enter your first name : ");
name = Console.ReadLine();
Console.WriteLine("Your name is " + name);
Console.ReadKey();
The variable name is declared but not assigned a value,
then the console uses the "Write()" method.
The Write() method is similar to WriteLine() but instead of writing some text and then setting the cursor on a new line it just writes it on where ever the cursor is, please compile that code to understand visually!
Once the message is displayed, we use the Console.ReadLine() to read data from where ever the cursor was to the last character entered in the console.
You cannot explicity ReadLine() a datatype other than a string, to if you were to add data to
an int variable you would have to convert the ReadLine() data to an int which will be explained in another lesson.
That basicly sums up the introduction to variables lesson, hope it was fun :P
Beginning C# Lesson 1 - The structure of a .cs file
Beginning C# Lesson 2 - Methods and stuff
Normally when you read lots of "Learn X programming book", you can recognise a pattern in there layout, most of them start of by making a program that doesn’t do much, then explaining what a variable is and a few chapters later they explain about methods. As a student do not like that layout because I want to know how the structure of the program should look, and how it works before I start adding stuff to it.
For those who suffer short term memory loss, a general structure of a C# source code is:
This consists of what class library’s to include, the namespace, classes and the methods inside the class.
In this instance, the class “Program” has a single method inside called “Main”, this method is unique in every program because “Main” is the programs entry point. In other words, when the program has finished initialized the very first method it will execute is “Main”, if it is not there it would crash, luckily Visual Studio 2008 won’t let you compile a program without this method.
Press the Green arrow at the top of Visual Studio to debug or press F5.
Lets analyse the method “Main”:
static void Main()
“static” - Method is pre loaded into memory when the program initialises, we need the “Main” method to load up on initialisation so that it knows that there is an “Entry” point to the application, static methods can be used inside other static methods without having to create a declaration (instantiation) of them.
“void” – Methods can return data when they end, void means that when this method has finished it will not return any data
“Main” – The name of the method created, you cant have more than one name of a method declared in a class as the compiler will assume its the same method and crash, you can overload methods which will be discussed later
“()” – Methods can accept input, you can specify what variable you want to input inside the parenthisis for example (string name)
As mentioned, a Class can have more than one method inside it, let’s create a program that has more than a single method.
Create a new project called firstprogram and change the text to the following:
The class “Program” has two methods, Main and MakeAMessage.
Method “Main” writes a line of text, then executes the “MakeAMessage” method (thus writing another line of text), when the method “MakeAMessage” has no more statements, it will end and the “Main” method resumes, waiting for a user to input a character to close.
Programming is fun as there are many ways to perform the same outcome, the following source shows the same functionality as the first program but this time showing the methods returned data in a WriteLine() statement.
Before the method “MakeAMessage” was written as “static void MakeAMessage()” and now it has changed to “static string MakeAMessage()”, void changed to string.
“void” means that the method does not return any data, changing it to string means that the method now returns a “string” variable. So when the method ends it will send the “string” variable as a value to whatever method called it. In this example it sends the returned value “This is returned from the MakeAMessage method” to the “WriteLine()” method from the “Console” class.
In other words the Console writes what the returned data from the MakeAMessage method.
Methods as mentioned can also have variables entered as input as well as returning data as output,to do this we specify the data type (What type of data ie string or decimal, and what the variable will be called and referred to)and the variables name to use inside the method.
MakeAMessage(string messageText) – string is the data type as we want to enter a string of characters , and it returns the variable data from “messageText” which we declared in the methods input (also known as arguments or parameters).
Another thing to look at is the WriteLIne() method called in the Main method, it allows us to enter a string value into the “MakeAMessage” method as input.
Dont forget to practice methods, methods that return data, and methods that can allow arguments.
For those who suffer short term memory loss, a general structure of a C# source code is:
This consists of what class library’s to include, the namespace, classes and the methods inside the class.
In this instance, the class “Program” has a single method inside called “Main”, this method is unique in every program because “Main” is the programs entry point. In other words, when the program has finished initialized the very first method it will execute is “Main”, if it is not there it would crash, luckily Visual Studio 2008 won’t let you compile a program without this method.
Press the Green arrow at the top of Visual Studio to debug or press F5.
Lets analyse the method “Main”:
static void Main()
“static” - Method is pre loaded into memory when the program initialises, we need the “Main” method to load up on initialisation so that it knows that there is an “Entry” point to the application, static methods can be used inside other static methods without having to create a declaration (instantiation) of them.
“void” – Methods can return data when they end, void means that when this method has finished it will not return any data
“Main” – The name of the method created, you cant have more than one name of a method declared in a class as the compiler will assume its the same method and crash, you can overload methods which will be discussed later
“()” – Methods can accept input, you can specify what variable you want to input inside the parenthisis for example (string name)
As mentioned, a Class can have more than one method inside it, let’s create a program that has more than a single method.
Create a new project called firstprogram and change the text to the following:
The class “Program” has two methods, Main and MakeAMessage.
Method “Main” writes a line of text, then executes the “MakeAMessage” method (thus writing another line of text), when the method “MakeAMessage” has no more statements, it will end and the “Main” method resumes, waiting for a user to input a character to close.
Programming is fun as there are many ways to perform the same outcome, the following source shows the same functionality as the first program but this time showing the methods returned data in a WriteLine() statement.
Before the method “MakeAMessage” was written as “static void MakeAMessage()” and now it has changed to “static string MakeAMessage()”, void changed to string.
“void” means that the method does not return any data, changing it to string means that the method now returns a “string” variable. So when the method ends it will send the “string” variable as a value to whatever method called it. In this example it sends the returned value “This is returned from the MakeAMessage method” to the “WriteLine()” method from the “Console” class.
In other words the Console writes what the returned data from the MakeAMessage method.
Methods as mentioned can also have variables entered as input as well as returning data as output,to do this we specify the data type (What type of data ie string or decimal, and what the variable will be called and referred to)and the variables name to use inside the method.
MakeAMessage(string messageText) – string is the data type as we want to enter a string of characters , and it returns the variable data from “messageText” which we declared in the methods input (also known as arguments or parameters).
Another thing to look at is the WriteLIne() method called in the Main method, it allows us to enter a string value into the “MakeAMessage” method as input.
Dont forget to practice methods, methods that return data, and methods that can allow arguments.
Beginning C# Lesson 0 - Defining C#
Source code is a text file with a .cs extension in C# (console,windows,WPF... apps).
Integrated Development Environments’ such as "Visual Studio 2008" and "SharpDevelop" provide a software developer with tools to design, write, implement and analyse their applications, the actual source however, is just a textile.
This lesson is aimed at beginner C# programmers, who either want to learn from the beginning (no prior programming knowledge requires just basic computer knowledge), or are looking to learn a new language.
Let’s start with some general programming theory!
What is a program?
A program is an object (.exe, .OthereExtension) that can perform a series of steps, the steps the program can invoke (execute) are stated inside a programs “source code”.
Source code as mentioned is a text file which is then feed into a “Compiler” or an “Interpreter”.
A Compiler converts the source into an object such as a exe while an interpreter reads the source code in “real time”(or for computer literate psudo-realtime) into a running program for example a “Browser” such as Firefox reads HTML source code and renders the data on screen.
What is C#?
C# is an “Object Orientated Programming Language” (OOP) which means instead of running an instruction procedurally line by line as statements, the compiler uses “objects” to send and receive data. The concept of OOP is to model programs based on the real world, for example there could be an object called “Car” that has some properties such as “Number of wheels”, “Max speed”, “Vendor”, and the Car object may have some steps it can perform “Accelerate”, “Reverse”, “Listen to the journey CD”, the car is an object, and we can send data from this object to other objects but i will explain more about this concept later.
C# uses the .Net environment which means that many of the syntax (keywords used inside a language) that are used only work on a system that has the .Net framework installed (Windows computers), so if you’re looking to program on a Mac or Linux, the programs won’t work as natively as you want, of course there are applications on Mac and Linux that simulate .net so the programs work, but .Net is focused on windows and is founded by Microsoft.
What is C# good for?
C# is good for allot of things, there is a class library called “XNA” that allows developers to make retail games, many of them are powerful and every “Xbox360 Market Place” game that is developed by a small business is made by this, however it is not as powerful and customization than another close language called “C++”, the main difference is that in C# you can make a game quickly, with less hassle, and it is more manageable to extend and maintain than C++. And as C# is still in development and version four is being released soon, it is improving all the time.
C# is good for web applications, ASP.net allows developers to make web forms or other web content, it allows socket programming to send and receive data from ports and other cool stuff.
Overall it is a strong language as many of its features and code style is from C (as C# is from the C programming language family), and can make enterprise applications that are secure, perform fast and easy to maintain, this however is up to you as any programming language requires you to explore its inner workings and learn new stuff frequently.
Integrated Development Environments’ such as "Visual Studio 2008" and "SharpDevelop" provide a software developer with tools to design, write, implement and analyse their applications, the actual source however, is just a textile.
This lesson is aimed at beginner C# programmers, who either want to learn from the beginning (no prior programming knowledge requires just basic computer knowledge), or are looking to learn a new language.
Let’s start with some general programming theory!
What is a program?
A program is an object (.exe, .OthereExtension) that can perform a series of steps, the steps the program can invoke (execute) are stated inside a programs “source code”.
Source code as mentioned is a text file which is then feed into a “Compiler” or an “Interpreter”.
A Compiler converts the source into an object such as a exe while an interpreter reads the source code in “real time”(or for computer literate psudo-realtime) into a running program for example a “Browser” such as Firefox reads HTML source code and renders the data on screen.
What is C#?
C# is an “Object Orientated Programming Language” (OOP) which means instead of running an instruction procedurally line by line as statements, the compiler uses “objects” to send and receive data. The concept of OOP is to model programs based on the real world, for example there could be an object called “Car” that has some properties such as “Number of wheels”, “Max speed”, “Vendor”, and the Car object may have some steps it can perform “Accelerate”, “Reverse”, “Listen to the journey CD”, the car is an object, and we can send data from this object to other objects but i will explain more about this concept later.
C# uses the .Net environment which means that many of the syntax (keywords used inside a language) that are used only work on a system that has the .Net framework installed (Windows computers), so if you’re looking to program on a Mac or Linux, the programs won’t work as natively as you want, of course there are applications on Mac and Linux that simulate .net so the programs work, but .Net is focused on windows and is founded by Microsoft.
What is C# good for?
C# is good for allot of things, there is a class library called “XNA” that allows developers to make retail games, many of them are powerful and every “Xbox360 Market Place” game that is developed by a small business is made by this, however it is not as powerful and customization than another close language called “C++”, the main difference is that in C# you can make a game quickly, with less hassle, and it is more manageable to extend and maintain than C++. And as C# is still in development and version four is being released soon, it is improving all the time.
C# is good for web applications, ASP.net allows developers to make web forms or other web content, it allows socket programming to send and receive data from ports and other cool stuff.
Overall it is a strong language as many of its features and code style is from C (as C# is from the C programming language family), and can make enterprise applications that are secure, perform fast and easy to maintain, this however is up to you as any programming language requires you to explore its inner workings and learn new stuff frequently.
Monday 20 July 2009
Secured Authentication
This open source project that i made a while a go is
for developers who want to learn some Ole-db database
programming methods in a practical exposure.
The Database file goes into your C: driver but of course,
if you read the source you would know that...
Get the file here
It isn't fully optimized so makes changes when you see fit.
for developers who want to learn some Ole-db database
programming methods in a practical exposure.
The Database file goes into your C: driver but of course,
if you read the source you would know that...
Get the file here
It isn't fully optimized so makes changes when you see fit.
Monday 13 July 2009
Three C# Performance boosting tips with strings!
From my short time of programming in C# i have seen some professional
developers using program structures that impact on performance,
when there is a faster alternative.
Tip 1
When comparing strings do not:
if (stringOne != stringTwo)
{
}
As that creates copy's of both variables, evaluates them and returns a result,
a better alternative is to use:
if (string.Compare(stringOne,stringTwo,false)==0)
{
}
This words directly with the string (remember instantiating a string is simply
creating an object from the String class...
Another benefit is that the third parameter corresponds to if it ignores the case
of the string's, thus saving the "stringOne.ToUpper()" syntax!
Tip 2
Do not assign strings magic data when in a loop, use the StringBuilder object to
stop the duplication of variables!
StringBuilder myString = new StringBuilder();
myString.Capacity = 10000;
for (int i = 0; i <>
{
myString.Append(i.ToString());
}
I done a small test against the conventional algorithm:
string myString = string.Empty;
for (int i = 0; i <>
{
myString += i.ToString();
}
The StringBuilder version gave me a result of 0.0038292 seconds while
the conventional method gave me a result of 0.3770280 seconds.
... That is 9746 times slower than the string builder.
Tip 3
The StringBuilder is fast but only when a loop with 100 > iterations is used!
I have seen developers use StringBuilder for concatenating 10 strings, that
is negativity impacting memory and CPU threads.
developers using program structures that impact on performance,
when there is a faster alternative.
Tip 1
When comparing strings do not:
if (stringOne != stringTwo)
{
}
As that creates copy's of both variables, evaluates them and returns a result,
a better alternative is to use:
if (string.Compare(stringOne,stringTwo,false)==0)
{
}
This words directly with the string (remember instantiating a string is simply
creating an object from the String class...
Another benefit is that the third parameter corresponds to if it ignores the case
of the string's, thus saving the "stringOne.ToUpper()" syntax!
Tip 2
Do not assign strings magic data when in a loop, use the StringBuilder object to
stop the duplication of variables!
StringBuilder myString = new StringBuilder();
myString.Capacity = 10000;
for (int i = 0; i <>
{
myString.Append(i.ToString());
}
I done a small test against the conventional algorithm:
string myString = string.Empty;
for (int i = 0; i <>
{
myString += i.ToString();
}
The StringBuilder version gave me a result of 0.0038292 seconds while
the conventional method gave me a result of 0.3770280 seconds.
... That is 9746 times slower than the string builder.
Tip 3
The StringBuilder is fast but only when a loop with 100 > iterations is used!
I have seen developers use StringBuilder for concatenating 10 strings, that
is negativity impacting memory and CPU threads.
Subscribe to:
Posts (Atom)