C# (pronounced "C sharp") is a modern, object-oriented programming language developed by Microsoft as part of its .NET initiative. The first version of the C# compiler was released in June 2000 as a beta version.
Evolution of C#
In the early 2000s, C# went through several iterations:
- C# 1.0 (2000): The initial release, which focused on building Windows applications.
- C# 1.1 (2003): Introduced support for generics, iterators, and partial classes.
- C# 2.0 (2005): Added features like anonymous methods, lambda expressions, and partial methods.
Xamarin's Impact (2004)
In 2004, Microsoft released Xamarin, a new framework that allowed developers to create cross-platform applications using C#. This marked a significant milestone in the evolution of C#, as it opened up new possibilities for building apps that could run on multiple platforms, including Windows, Android, and iOS.
Key Features of Early C#
Some key features that were introduced in early versions of C# include:
- Object-oriented programming: C# is an object-oriented language that supports concepts like classes, interfaces, inheritance, polymorphism, and encapsulation.
- Multi-paradigm programming: C# allows developers to write code using different programming paradigms, such as procedural, functional, and declarative styles.
- Garbage collection: C# uses a garbage collector to manage memory allocation and deallocation, making it easier for developers to write robust code.
- Nullable types: The language provides nullable types that guard against variables that don't refer to allocated objects, helping prevent null reference exceptions.
- Exception handling: C# provides a structured and extensible approach to error detection and recovery through its exception handling mechanisms.
- Lambda expressions: C# introduced lambda expressions, which enable developers to write concise and expressive code using anonymous functions.
- Language Integrated Query (LINQ): LINQ allows developers to query data structures using a SQL-like syntax, making it easier to manipulate and retrieve data.
Namespace and Assembly
In C#, a namespace is a container for related classes. It's a collection of classes that can be used throughout an application. A namespace helps organize code by grouping related classes together.
An assembly, on the other hand, is a file automatically generated by the compiler after successful compilation of every .NET application. Assemblies can be either Dynamic Link Layer (DLL) or executable files (.exe). The assembly gets updated only once for an application and upon each subsequent compilation, it does not get recreated.
Here's a commented example code snippet in C# to illustrate these concepts:
// Define a namespace called "MyNamespace"
namespace MyNamespace
{
// Define a class called "Calculator" within the namespace
public class Calculator
{
// Method to calculate the sum of two numbers
public int Add(int x, int y)
{
return x + y;
}
}
}
This example defines a namespace MyNamespace
with a class Calculator
that contains a method to calculate the sum of two numbers. The assembly for
this code would be generated as a DLL file.
A name that we can assign for:
- A class, interface, struct, delegate or enum member
- A variable
- A namespace
An identifier is a series of characters consisting of:
- Unicode letter characters
- Decimal digit characters
- Unicode connecting characters
- Unicode combining characters
- Unicode formatting characters
Characteristics:
- Should start with a letter or underscore (-)
- Does not contain any spaces or symbols
- Case sensitive
- Should not be a C# keyword
- Prefer Pascal casing for naming classes, structs, methods, properties, or constant fields.
- Typically prefix interfaces with a capital letter "I".
- Alternatively, use Pascal casing for interface names.
- Use camel case for naming method arguments, private fields, and local variables.
- Prefix private fields with an underscore (_) character.
- Always use meaningful and self-explanatory names for your classes, methods, and properties.
- Predefined words reserved by the C# compiler.
- Examples:
class
,interface
,namespace
,public
,private
- Cannot be used as identifiers.
- If you want to use a keyword as an identifier, prefix it with the
@
character.
- These keywords have a special meaning within the context of your code.
- Predefined Data Types
- Integer
- Boolean
- Float
- User defined Data Types
- Enumerations
- Structure
-
Predefined Data Types
- Objects
- Strings
-
User defined Data Types
- Classes
- Interface
-
int: Represents whole numbers.
- Example:
1
,-5
,100
- Example:
-
float: Represents single-precision floating-point numbers.
- Example:
3.14F
,-0.001F
- Example:
-
double: Represents double-precision floating-point numbers.
- Example:
3.14159
,-0.0001
- Example:
-
char: Represents a single Unicode character.
- Example:
'A'
,'z'
,'1'
- Example:
-
string: Represents a sequence of characters.
- Example:
"Hello, World!"
,"C# Programming"
- Example:
-
bool: Represents boolean values (true or false).
- Example:
true
,false
- Example:
- A primitive type/value type data type.
- Used to create a single variable related data of various data types.
struct
keyword is used for structure creation.
Example:
using System;
struct Novel
{
public string title;
public string author;
public int bookID;
}
- A special class that represents a collection of constants which are unchangeable and read-only variables.
Example:
enum Pressure
{
Low,
Medium,
High
}
Pressure p = Pressure.Medium; // creating object from pressure enum.
- A name given to a storage area that is used to store values of various data types.
- Each variable in C# needs to have a specific type, which determines the size and layout of the variable's memory.
- A fixed value used by a predefined variable which cannot be modified when we are executing the program.
- Mostly suitable for constant type variable declarations.
Syntax: data_type variable_name;
Examples:
int age;
double pi;
char grade;
string name;
bool isStudent;
Syntax: data_type variable_name = value;
Examples:
int age = 20;
char grade = 'A';
string name = "John Doe";
bool isStudent = true;
Direction: char -> int -> long -> float -> double
Example:
int num = 10;
double doubleNum = num;
Direction: double -> float -> long -> int -> char
Example:
double pi = 3.14;
int intPi = (int)pi;
ToBoolean
: Converts a type to a Boolean value, where possible.ToByte
: Converts a type to a byte.ToChar
: Converts a type to a single Unicode character, if possible.ToDecimal
: Converts a floating point or integer type to a decimal type.ToDouble
: Converts a type to a double type.ToInt32
: Converts a type to a 32-bit integer.ToInt64
: Converts a type to a 64-bit integer.ToUInt16
: Converts a type to an unsigned int type.ToString
: Converts a type to a string.ToType
: Converts a type to a specified type.
int sum = 50;
double height = 145.45;
bool powerStatus = true;
Console.WriteLine(Convert.ToString(sum));
Console.WriteLine(Convert.ToDouble(sum));
Console.WriteLine(Convert.ToInt32(height));
Console.WriteLine(Convert.ToString(powerStatus));
Console.WriteLine(Convert.ToUInt64(height));
Scope of a variable is its lifetime in a program.
- Class level scope: Can be accessed anywhere within the class.
- Method level scope: Can be accessed within a method.
- Block level scope: Can be accessed within a specific block of the program.
Console input allows a program to take input from the user through the console.
Example:
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
Console.WriteLine("Your name is: " + name);
Console output allows the program to interact with the user by displaying information.
Examples:
Console.WriteLine("Hello, World!");
Console.Write("This is my life ");
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
\'
– Output a Single quote\"
– Output a double quote\\
– Output a Backslash\n
– Insert a newline\r
– Insert a carriage-return\t
– Insert a tab\0
– Insert a null character\b
– Insert a backspace@
- Verbatim String (Outputs same string as seen in code)
In C#, the operators can be divided into the following groups:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Bitwise operators
The behavior of these operators is quite similar to their behavior in the C and Java languages.
// Arithmetic Operators
int a = 10, b = 3;
Console.WriteLine(a + b); // Output: 13
Console.WriteLine(a - b); // Output: 7
Console.WriteLine(a * b); // Output: 30
Console.WriteLine(a / b); // Output: 3 (integer division)
Console.WriteLine(a % b); // Output: 1 (remainder)
// Assignment Operators
int x = 5;
x += 3; // Equivalent to x = x + 3
Console.WriteLine(x); // Output: 8
// Comparison Operators
Console.WriteLine(a > b); // Output: True
Console.WriteLine(a == b); // Output: False
// Logical Operators
bool p = true, q = false;
Console.WriteLine(p && q); // Output: False
Console.WriteLine(p || q); // Output: True
Console.WriteLine(!p); // Output: False
// Bitwise Operators
int m = 5, n = 3;
Console.WriteLine(m & n); // Output: 1 (bitwise AND)
Console.WriteLine(m | n); // Output: 7 (bitwise OR)
Console.WriteLine(m ^ n); // Output: 6 (bitwise XOR)
- One class can have a main method normally in a program.
- The main method is considered as the entry point of execution in any program.
To specify which main method to use when multiple exist, use the following command at the command prompt:
> csc filename.cs /main:classname
Where:
filename
is the name of the file where the code is storedclassname
is the class containing the Main method you want to use
This allows you to specify which class's Main method should be used as the entry point when multiple classes in your project have a Main method.