C# Language Primer
C# Language Primer
C# (pronounced "C sharp") is the flagship language of the .NET Framework. It combines the power of C++ with the productivity of Visual Basic.
Hello World
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, Flamenet Developer Network!");
}
}
Classes and Objects
public class Employee
{
// Fields
private string _firstName;
private string _lastName;
// Properties
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public string FullName
{
get { return _firstName + " " + _lastName; }
}
// Constructor
public Employee(string firstName, string lastName)
{
_firstName = firstName;
_lastName = lastName;
}
// Method
public override string ToString()
{
return FullName;
}
}
// Usage
Employee emp = new Employee("John", "Smith");
Console.WriteLine(emp.FullName); // "John Smith"
Data Types
| C# Type | .NET Type | Description |
|---|---|---|
| int | System.Int32 | 32-bit integer |
| long | System.Int64 | 64-bit integer |
| float | System.Single | 32-bit floating point |
| double | System.Double | 64-bit floating point |
| decimal | System.Decimal | 128-bit precise (financial) |
| bool | System.Boolean | true or false |
| string | System.String | Unicode string (immutable) |
| object | System.Object | Base type of all types |
Control Flow
// if-else
if (age >= 18)
Console.WriteLine("Adult");
else
Console.WriteLine("Minor");
// switch
switch (role)
{
case "admin":
Console.WriteLine("Administrator");
break;
case "mod":
Console.WriteLine("Moderator");
break;
default:
Console.WriteLine("Member");
break;
}
// for loop
for (int i = 0; i < 10; i++)
Console.WriteLine(i);
// foreach
string[] names = { "Alice", "Bob", "Charlie" };
foreach (string name in names)
Console.WriteLine(name);
// while
while (reader.Read())
Console.WriteLine(reader["Name"]);
Exception Handling
try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
Console.WriteLine("Cleanup code runs always.");
}