- Chapter – 1 C# Basic
- Chapter 2: Control Structures
- Chapter 3: Methods and Functions
- Chapter 4: Object-Oriented Programming
- Chapter 5: Advanced OOPs Concepts
- Chapter 6: Exception Handling
- Chapter 7: Collections and Generics
- Chapter 8: Delegates and Events
- Chapter 9: LINQ (Language Integrated Query)
- Chapter 10: File I/O
- Chapter 11: Multithreading & Parallel Programming
- Chapter 12: Network Programming
- Chapter 13: Database Connectivity
- Chapter 14: Windows Forms and WPF
- Chapter 15: Security in C#
- Download File Link
Chapter – 1 C# Basic
Overview of C#
C# is a modern, object-oriented programming language developed by Microsoft for building a wide range of applications.
First C# Program
using System; class Program { static void Main() { Console.WriteLine("Hello, World!"); } }
Syntax and Structure
C# programs are organized into classes and namespaces.
namespace MyApp { class Program { static void Main() { // Code here } } }
Variables and Data Types
Variables store data, and C# supports various data types.
int number = 10; string message = "Hello"; bool isActive = true;
Constants and Enumeration
Constants are immutable values, and enumerations define a set of named constants.
const double Pi = 3.14; enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; Days today = Days.Monday;
Operations in C#
C# supports arithmetic, relational, and logical operations.
int a = 5, b = 3; int sum = a + b; bool isEqual = (a == b); bool isActive = true && false;
Chapter 2: Control Structures
Conditional Statements
Control flow using if
, else
, and switch
.
if (a > b) { Console.WriteLine("a is greater than b"); } else if (a == b) { Console.WriteLine("a is equal to b"); } else { Console.WriteLine("a is less than b"); } switch (today) { case Days.Monday: Console.WriteLine("It's Monday"); break; // Other cases }
Looping Construct
Repeat code using for
, while
, and do-while
.
for (int i = 0; i < 5; i++) { Console.WriteLine(i); } int j = 0; while (j < 5) { Console.WriteLine(j); j++; } int k = 0; do { Console.WriteLine(k); k++; } while (k < 5);
Jump Statements
Control flow with break
, continue
, and return
.
for (int i = 0; i < 10; i++) { if (i == 5) break; if (i % 2 == 0) continue; Console.WriteLine(i); }
Chapter 3: Methods and Functions
Defining Methods
Methods encapsulate reusable code.
void PrintMessage(string message) { Console.WriteLine(message); }
Method Parameters and Return Type
Methods can have parameters and return values.
int Add(int x, int y) { return x + y; }
Method Overloading
Multiple methods with the same name but different parameters.
int Add(int x, int y) { return x + y; } double Add(double x, double y) { return x + y; }
Recursion
Methods can call themselves.
int Factorial(int n) { if (n <= 1) return 1; return n * Factorial(n - 1); }
Lambda Functions
Inline, anonymous methods.
Func<int, int, int> add = (x, y) => x + y; Console.WriteLine(add(2, 3));
Chapter 4: Object-Oriented Programming
Introduction to OOP
OOP concepts include encapsulation, inheritance, and polymorphism.
Classes and Objects
Classes are blueprints; objects are instances.
class Car { public string Model { get; set; } } Car myCar = new Car(); myCar.Model = "Toyota";
Access Modifiers
Control access to class members.
class Car { private string model; public void SetModel(string model) { this.model = model; } }
Constructors and Destructors
Special methods for initializing and cleaning up.
class Car { public Car() { Console.WriteLine("Car created"); } ~Car() { Console.WriteLine("Car destroyed"); } }
Inheritance
Derive new classes from existing ones.
class Vehicle { public void Move() { Console.WriteLine("Moving"); } } class Car : Vehicle { public void Honk() { Console.WriteLine("Honk"); } }
Polymorphism
Methods behave differently based on the object.
class Animal { public virtual void Speak() { Console.WriteLine("Animal sound"); } } class Dog : Animal { public override void Speak() { Console.WriteLine("Bark"); } }
Encapsulation
Restrict direct access to data.
class Person { private string name; public string Name { get { return name; } set { name = value; } } }
Abstraction
Hide complex implementation details.
abstract class Shape { public abstract void Draw(); } class Circle : Shape { public override void Draw() { Console.WriteLine("Drawing Circle"); } }
Chapter 5: Advanced OOPs Concepts
Interfaces
Define a contract that classes must implement.
interface IMovable { void Move(); } class Car : IMovable { public void Move() { Console.WriteLine("Car is moving"); } }
Abstract Classes
Cannot be instantiated, but can be subclassed.
abstract class Animal { public abstract void MakeSound(); } class Dog : Animal { public override void MakeSound() { Console.WriteLine("Bark"); } }
Sealed Classes
Cannot be inherited.
sealed class FinalClass { // Implementation }
Static Classes and Members
Contain only static members.
static class Utility { public static void PrintMessage(string message) { Console.WriteLine(message); } }
Partial Classes and Methods
Split a class or method into multiple files.
partial class Car { public void Drive() { Console.WriteLine("Driving"); } }
Nested Classes
Classes defined within other classes.
class OuterClass { class InnerClass { // Implementation } }
Chapter 6: Exception Handling
Understanding Exceptions
Exceptions are runtime errors that can be handled.
Try, Catch, Finally Blocks
Handle exceptions and clean up resources.
try { int result = 10 / 0; } catch (DivideByZeroException ex) { Console.WriteLine("Cannot divide by zero"); } finally { Console.WriteLine("Finally block executed"); }
Throwing Exceptions
Explicitly throw exceptions.
void CheckAge(int age) { if (age < 18) { throw new ArgumentException("Age must be 18 or older"); } }
Creating Custom Exceptions
Define user-defined exceptions.
class MyCustomException : Exception { public MyCustomException(string message) : base(message) { } }
Chapter 7: Collections and Generics
Arrays
Fixed-size, ordered collection of elements.
int[] numbers = { 1, 2, 3, 4, 5 };
Lists
Dynamic-size, ordered collection.
List<int> numbers = new List<int> { 1, 2, 3 }; numbers.Add(4);
Dictionaries
Key-value pairs collection.
Dictionary<string, int> ages = new Dictionary<string, int> { { "Alice", 25 }, { "Bob", 30 } };
Sets
Unordered collection of unique elements.
HashSet<int> numbers = new HashSet<int> { 1, 2, 3, 3 }; // { 1, 2, 3 }
Stacks and Queues
LIFO and FIFO collections.
Stack<int> stack = new Stack<int>(); stack.Push(1); stack.Push(2); int top = stack.Pop(); Queue<int> queue = new Queue<int>(); queue.Enqueue(1); queue.Enqueue(2); int front = queue.Dequeue();
Generic Collections
Type-safe collections.
List<string> names = new List<string>(); names.Add("Alice"); names.Add("Bob");
Iterators and Enumerators
Traverse through collections.
foreach (int number in numbers) { Console.WriteLine(number); }
Chapter 8: Delegates and Events
Understanding Delegates
Delegates are type-safe function pointers.
delegate void PrintMessage(string message); void Print(string message) { Console.WriteLine(message); } PrintMessage pm = Print; pm("Hello, World!");
Delegate Types
Single-cast and multi-cast delegates.
PrintMessage pm1 = Print; PrintMessage pm2 = Print; PrintMessage multiPm = pm1 + pm2; multiPm("Hello");
Events and Event Handling
Events are a way for objects to communicate.
class Publisher { public event EventHandler EventOccurred; public void TriggerEvent() { if (EventOccurred != null) { EventOccurred(this, EventArgs.Empty); } } } class Subscriber { public void OnEventOccurred(object sender, EventArgs e) { Console.WriteLine("Event occurred"); } } Publisher p = new Publisher(); Subscriber s = new Subscriber(); p.EventOccurred += s.OnEventOccurred; p.TriggerEvent();
Anonymous Methods
Inline methods without a name.
PrintMessage pm = delegate (string message) { Console.WriteLine(message); }; pm("Hello, World!");
Chapter 9: LINQ (Language Integrated Query)
Introduction to LINQ
LINQ provides querying capabilities to .NET languages.
LINQ Syntax
Query collections using LINQ syntax.
int[] numbers = { 1, 2, 3, 4, 5 }; var evenNumbers = from num in numbers where num % 2 == 0 select num;
LINQ to Objects
Query in-memory collections.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; var evenNumbers = numbers.Where(num => num % 2 == 0);
LINQ to SQL
Query relational databases.
var query = from customer in dbContext.Customers where customer.City == "London" select customer;
LINQ to XML
Query and manipulate XML data.
XDocument xdoc = XDocument.Load("data.xml"); var names = from el in xdoc.Descendants("name") select el.Value;
Chapter 10: File I/O
Reading and Writing Files
Handle file operations.
File.WriteAllText("test.txt", "Hello, World!"); string content = File.ReadAllText("test.txt");
Working with Streams
Read and write streams of data.
using (StreamWriter writer = new StreamWriter("test.txt")) { writer.WriteLine("Hello, World!"); } using (StreamReader reader = new StreamReader("test.txt")) { string content = reader.ReadToEnd(); }
File and Directory Operations
Manipulate file system entities.
File.Create("newfile.txt"); Directory.CreateDirectory("newfolder");
Chapter 11: Multithreading & Parallel Programming
Introduction to Multithreading
Run code in parallel using threads.
Creating and Managing Threads
Create and control threads.
Thread thread = new Thread(() => Console.WriteLine("Hello from thread")); thread.Start(); thread.Join();
Thread Synchronization
Coordinate thread activities.
object lockObject = new object(); lock (lockObject) { // Thread-safe code }
Task Parallel Library (TPL)
High-level parallelism with tasks.
Task.Run(() => Console.WriteLine("Hello from Task"));
async and await
Asynchronous programming model.
async Task<string> GetMessageAsync() { await Task.Delay(1000); return "Hello, World!"; } string message = await GetMessageAsync(); Console.WriteLine(message);
Chapter 12: Network Programming
Introduction to Networking
Network communication basics.
Working with Sockets
Low-level network communication.
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect("example.com", 80);
TCP and UDP Communication
Reliable and unreliable communication.
TcpClient client = new TcpClient("example.com", 80); NetworkStream stream = client.GetStream(); byte[] data = Encoding.ASCII.GetBytes("Hello"); stream.Write(data, 0, data.Length);
HTTP Client and Web Requests
Work with HTTP.
HttpClient client = new HttpClient(); string response = await client.GetStringAsync("https://example.com"); Console.WriteLine(response);
Chapter 13: Database Connectivity
Introduction to ADO.NET
Access and manipulate databases.
Connecting to Databases
Establish database connections.
SqlConnection connection = new SqlConnection("your_connection_string"); connection.Open();
Executing Commands
Run SQL commands.
SqlCommand command = new SqlCommand("SELECT * FROM Users", connection); SqlDataReader reader = command.ExecuteReader();
Using Data Readers
Read data from a database.
while (reader.Read()) { Console.WriteLine(reader["Name"]); }
Using Data Sets and Data Adapters
Manage in-memory data.
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Users", connection); DataSet dataSet = new DataSet(); adapter.Fill(dataSet);
Entity Framework
ORM for database operations.
using (var context = new MyDbContext()) { var users = context.Users.ToList(); }
Chapter 14: Windows Forms and WPF
Introduction to Windows Forms
Build graphical applications.
Basic Controls and Events
Use controls and handle events.
Button button = new Button(); button.Text = "Click Me"; button.Click += (s, e) => MessageBox.Show("Hello!");
Layout Management
Arrange controls in a form.
FlowLayoutPanel panel = new FlowLayoutPanel(); panel.Controls.Add(button); this.Controls.Add(panel);
Introduction to WPF
Modern UI framework for Windows applications.
Data Binding in WPF
Bind UI elements to data.
<TextBox Text="{Binding Name}" />
Styles and Templates in WPF
Customize the appearance of controls.
<Style TargetType="Button"> <Setter Property="Background" Value="LightBlue"/> </Style>
Chapter 15: Security in C#
Understanding Security
Principles of secure coding.
Authentication and Authorization
Control access to resources.
// Example using ASP.NET Identity
Encryption and Decryption
Secure data with cryptography.
using (Aes aes = Aes.Create()) { byte[] encrypted = Encrypt(data, aes.Key, aes.IV); byte[] decrypted = Decrypt(encrypted, aes.Key, aes.IV); }
Download File Link
Here you can download the Complete C# Cheat Sheet PDF.
Send download link to: