C Sharp for Beginners/Printable version
This is the print version of C Sharp for Beginners You won't see this message or any elements not part of the book's content when you print or preview this page. |
The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/C_Sharp_for_Beginners
Introduction
class HelloWorldProgram
{
public static void Main()
{
System.Console.WriteLine("Hello, world!"); // prints some text on to the screen
System.Console.ReadKey(); /* waits for the user
to press a key
*/
}
}
Hello World
Here is your first C# program:
class HelloWorldProgram
{
public static void Main()
{
System.Console.WriteLine("Hello, world!"); // prints some text on to the screen
System.Console.ReadKey(); /* waits for the user
to press a key
*/
}
}
Let's go through each line and see what they do:
class HelloWorldProgram
defines a class named "HelloWorldProgram". At this point, you can think of a class as a group of methods.public static void Main()
defines a method named "Main". A method is simply a code block (a container) containing some statements. TheMain()
method is special because it is the first thing that is run when your program is started.System.Console.WriteLine("Hello, world!");
is a statement. A statement performs an action, which in this case is printing (outputting) "Hello, world!" to the screen.System.Console.ReadKey();
is another statement. This time, it waits for the user to press a key.- After the last statement is executed, the program terminates.
Here's what should have happened:
- You start the program.
- The program outputs "Hello, world!" and waits.
- You press a key.
- The program closes.
Comments
[edit | edit source]Comments are pieces of text which are ignored by the compiler. There are three types of comments, two of which were used in the hello world program above.
- A single line comment is produced by using a double slash (
//
) and tells the compiler to ignore the rest of the line. - A multiline comment is started by using a slash and an asterisk (
/*
) and ended using an asterisk and a slash (*/
). The compiler ignores everything in between, even if the comment stretches over multiple lines (hence the name). - A documentation comment is used to document classes, properties, and methods. They start with three slashes (
///
) and use various XML tags.
Although comments are useful for describing code, they should not be used to simply restate what the code does, i.e.:
int number = 12; // declares a variable and assigns 12 to it
Console.WriteLine(number); // prints 12 to the console
Instead, they should be used to explain why a code does something that way.
int number = 12; // 12 is the number of months in a year.
Console.WriteLine(number);
There are other solutions to this, as you will see soon.
Variables
Variables are simply places to store data like numbers, strings (text), arrays of numbers or strings, and other objects. Each variable can only store data of one type, and you must declare variables before attempting to set or get their values. Here is a sample program that uses variables:
class VariablesExample
{
public static void Main()
{
int number;
string myText;
number = 100;
System.Console.WriteLine(number);
myText = "Hello!";
System.Console.WriteLine(myText);
number = 200;
System.Console.WriteLine(number);
System.Console.ReadKey();
}
}
The output would be:
100 Hello! 200
You can see that variables are declared using the form [type] [variable name];
and are set using the =
operator. You can declare multiple variables of the same type by placing commas after each variable name:
int x, y, z;
If you want to set variables immediately after you declare them, you can use the form [type] [variable name] = [value];
:
class VariablesExample2
{
public static void Main()
{
int number = 100;
string myText = "Hello!";
System.Console.WriteLine(number);
System.Console.WriteLine(myText);
number = 200;
System.Console.WriteLine(number);
System.Console.ReadKey();
}
}
The output would be exactly the same as before.
Types
[edit | edit source]C# offers various types of variables besides int
and string
. Here is a short list of the available types:
bool
- stores true or false.byte
- stores an unsigned byte.sbyte
- stores a signed byte.char
- stores a single character:char theLetterA = 'a';
int
- stores an integer:int number = 100;
short
,long
- both store an integer.ushort
,uint
,ulong
- both store an unsigned integerfloat
- stores a floating-point number:float number = 3.14159;
double
- stores a double-precision floating-point number.decimal
- stores a quadruple-precision floating-point number.string
- stores a string, or a sequence of characters.
Note: a floating-point number is a number which can be fractional. For example, 3.14159 is a floating-point number while 314 is just an integer.
You may be wondering why there are so many types for storing integers and floating-point numbers. Signed integers can be negative as well as positive, while unsigned integers can only be positive. So, byte
, ushort
, uint
and ulong
can only store positive integers.
There are also different sizes for integers and floating-point numbers; a type with a bigger size has a bigger range than a type with a smaller size. Here are the sizes of the types:
byte, sbyte
- 8 bits, or 1 byte.byte
can store numbers from 0 to 255, whilesbyte
can store numbers from -128 to 127.short, ushort
- 16 bits, or 2 bytes.short
can store numbers from -32,768 to 32,767, whileushort
can store numbers from 0 to 65,535.int, uint
- 32 bits, or 4 bytes.int
can store numbers from negative 2 billion to positive 2 billion, whileuint
store numbers from 0 to 4 billion.long, ulong
- 64 bits, or 8 bytes.long
can store numbers from negative 9 million million million to positive 9 million million million, whileulong
can store numbers from 0 to 18 million million million.
You may also be wondering why there are small types when we could use the biggest available types (long
, decimal
). The answer is that most computers today are 32-bit, which means that they are designed to handle 32-bit numbers. 64-bit numbers are therefore slower to add, subtract, multiply, and divide.
Operators
Operators perform actions on data. There are three types of operators in C#:
- A unary operator has the form
[operator][object]
. An example is the negation operator:-number
gives younumber
with the opposite sign (ifnumber
was 12 you would get -12). - A binary operator has the form
[object 1] [operator] [object 2]
. An example is the assignment operator:number = 1234
setsnumber
to 1234. - A ternary operator has three objects on which it acts. C# only has one ternary operator, the conditional operator:
number == 1234 ? "good" : "bad"
gives you "good" ifnumber
is equal to 1234, but "bad" ifnumber
is not equal to 1234.
You can combine operators in almost any way you like. Here is an example incorporating many different operators:
class OperatorsExample
{
public static void Main()
{
int number = 0;
float anotherNumber = 1.234;
string someText = "lots of ";
number = number + 4; // number is now 4
anotherNumber += 2; // this is a shorter version of the above; it adds 2 to anotherNumber, making it 3.234
someText += "text"; // someText now contains "lots of text"
number = -number; // number is now -4
anotherNumber -= number * 2; // subtracts -8 from anotherNumber, making anotherNumber 11.234.
number++; // increments number, making it -3
anotherNumber = number++; // increments number but sets anotherNumber to the original number.
// number is now -2, and anotherNumber is -3.
number--; // decrements number, making it -3
anotherNumber = --number; // decrements number and sets anotherNumber to the new number.
anotherNumber = number = 1; // sets both anotherNumber and number to 1.
bool someBoolean;
// sets someBoolean to true if anotherNumber equals number, otherwise sets it to false
someBoolean = anotherNumber == number;
}
}
Prefix and Postfix
[edit | edit source]The ++
and --
operators can be placed before (prefix) or after (postfix) variables. There is a subtle difference between the two; if placed before, it increments or decrements and then returns the new value, and if placed after, it increments or decrements and returns the old value. For example:
int x, y;
x = 0;
x++;
++x;
// x is now 2...
y = x++; // y is now 2, x is now 3
x = 2; // x is now 2 again...
y = ++x; // y is now 3, x is now 3
Arrays
using System;
Public Class TwoD {
public static void Main(string [] args) { int[,]a = int[2,2]; int i,j; Console.WriteLine("Enter elements in the array:"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { a[i,j]=Convert.ToInt32(Console.ReadLine()); } } }
}
Making Decisions
If Statement:
[edit | edit source]The if statement in c# is so simple like other languages. The syntax for if statement is:
if(condition){
// Statements
}
Here is condition we can check some expression for true or false. For example 5 > 4 is true but 4 > 5 is false.
if(5 > 4){
Console.WriteLine("Yes five is still greater than 4");
}
Else part:
[edit | edit source]In the else part if if condition we can give statements which will execute if condition is false.
if(5 > 4){
Console.WriteLine("Yes five is still greater than four");
} else {
Console.WriteLine("Oh No! five is now no longer greater than four");
}
Looping
while (myInt < 10){ // do things... myInt++; }
Do loops are like while loops, except they always execute at least once.
do { // do things... } while (myVar != false);
for (int i=0; i < 10; i++){ if (i == 10) break; if (i % 2 == 0) continue; // do things }
Inheritance
As this is about getting started programming, we don't want to confuse you with too much complicated stuff.
You may sometimes see classes declared like this:
class MyClass : Form
{
...//
}
instead of just like this
class MyClass
{
...//
}
People Inheritance
It is common for You to inherit characteristics from your parents. You may have your Mother’s way of talking or your Father’s nose. This doesn't mean you are identical to your Parents, but certain characteristics come "built in" when you’re born.
Code Inheritance
When we write code, it could be useful to inherit a whole bunch of abilities from an existing class. Lets go with an example. There are two defined classes “Animal” and “Bird”, but the “Bird” class inherits from the Animal class.
class Animal
{
public string kindOfAnimal;
public string name;
....
}
class Bird : Animal // “Bird” class inherits from “Animal” class
{
public string featherColor;
…
}
In real world, a bird is a kind of animal, but it has some characteristics that don’t apply to all animals. So it makes sense for a Bird class to have all the characteristics of an Animal as well as some extra ones. In this case, we’ve identified one special field for birds only – featherColor. We're really saying "I'm defining a new class called ‘Bird’ but it must inherit everything from the “Animal” class too.";
When to Use Inheritance
Inheritance is best used in cases where what you're trying to achieve can mostly be done by an existing class and you just want to extend it or customize it. In the following example, the class "Guitarist" inherits three fields from the class "Musician" and adds two fields of its own. The colon “:” is the part that tells the computer to make the new class (Guitarist) inherit from the class written to the right of the colon.
public class Musician
{
public string name;
public int ageInYears;
....\\
}
public class Guitarist : Musician
{
public string guitarType;
public string guitarBrand;
}
Guitarist g = new Guitarist();
g.name = "JOHN ABC";
g.ageInYears = 25;
g.guitarType = ”Acoustic”;
g.guitarBrand = ”Gibson”;
When we create an instance of a “Guitarist”, we can immediately address the fields of both a Musician and a Guitarist (as long as they’re not private).