0% found this document useful (0 votes)
2 views5 pages

CSharp NET Core Guide

This beginner-friendly guide introduces C# and .NET Core, covering essential topics such as data types, object-oriented programming, and debugging techniques with practical examples. It highlights the differences between .NET Framework and .NET Core, emphasizes the importance of generics and collections, and provides insights into microservices architecture. The guide encourages hands-on practice through small projects and offers the option for expanded content on specific sections.

Uploaded by

kchandana2626
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views5 pages

CSharp NET Core Guide

This beginner-friendly guide introduces C# and .NET Core, covering essential topics such as data types, object-oriented programming, and debugging techniques with practical examples. It highlights the differences between .NET Framework and .NET Core, emphasizes the importance of generics and collections, and provides insights into microservices architecture. The guide encourages hands-on practice through small projects and offers the option for expanded content on specific sections.

Uploaded by

kchandana2626
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

C# & .

NET Core — Beginner-Friendly Guide

This guide covers core topics of C# and .NET Core in simple language, with short real-life examples and
code snippets.
If you want a deeper dive into any section, tell me which one and I'll expand it.

Introduction to .NET Core

Overview: .NET Core is a free, open-source, cross-platform framework for building modern applications
(web, desktop, cloud, microservices).
Characteristics: Cross-platform, modular, high-performance, supports multiple languages (C#, F#, VB), and
has a unified runtime (.NET).
Platform & Architecture: Uses a runtime (CoreCLR), libraries (CoreFX), and SDK tools. It's modular — you
reference only the packages you need.
Real-world example: Building a cross-platform web API that runs on Windows, Linux, and Docker containers.
Terminal: Create and run a simple .NET Core console app.
dotnet new console -o HelloApp
cd HelloApp
dotnet run

Introduction to C#

C# is a modern, object-oriented programming language used with the .NET platform. It's statically typed and
supports features like LINQ, async/await, and strong tooling.
Compilation & Execution: C# source code (.cs) is compiled into Intermediate Language (IL). The runtime
(CLR/CoreCLR) JIT-compiles IL to native code at runtime.
Simple C# program (Hello World).
using System;
class Program {
static void Main(){
Console.WriteLine("Hello, C# World!");
}
}

Data Types and Arrays in C#

Value types (stored on stack): int, double, bool, struct. Reference types (stored on heap): class, string,
arrays, delegates.
Boxing/unboxing: converting a value type to object (boxing) and back (unboxing). Avoid frequent boxing for
performance.
Arrays: single-dimensional, multi-dimensional, jagged arrays (array of arrays). Use arrays when size known;
use List<T> for dynamic collections.
Nullable types: use int? when a value type needs to represent 'no value'.
Var vs dynamic: var is compile-time typed (type inferred); dynamic is resolved at runtime (less safe).
Ref vs out: both pass by reference; out requires assignment in the method before returning; ref requires
initialization before calling.
Array examples.
int[] single = new int[]{1,2,3};
int[,] matrix = new int[2,3];
int[][] jagged = new int[2][]; jagged[0] = new[]{1,2};
Nullable type example.
int? possible = null; // Nullable int

Strings and StringBuilder

Strings are immutable. Concatenating many strings creates many intermediate objects. Use StringBuilder for
heavy string manipulation.
Equals() vs == : For strings, == is overridden to compare content. Equals() can allow culture/compare
options.
Using StringBuilder for efficient concatenation.
using System.Text;
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(' ');
sb.Append("World");
Console.WriteLine(sb.ToString());

Parsing & Conversion

Parse() throws exception if input invalid. TryParse() returns bool indicating success and avoids exceptions.
Convert.* methods handle nulls differently.
Use int.TryParse when input may be invalid (e.g., user input).
Safe parsing with TryParse.
string s = "123";
if (int.TryParse(s, out int val)) {
Console.WriteLine(val+1);
}

Debugging in C# / .NET

Use Visual Studio or Visual Studio Code (with C# extension) for debugging. Set breakpoints, inspect
variables, step over/into methods, and use the watch window.
Break conditions allow stopping only when a condition is met (e.g., i==100). Logging/tracing help diagnose
issues in production.

OOP with C# (Core Concepts)

Classes & Objects: classes define structure and behavior. Create objects (instances) from classes.
Inheritance: derived classes reuse/extend base class behavior. Use virtual and override for polymorphism.
Access Modifiers: private, protected, internal, public — control visibility. 'protected internal' combines
protections.
Abstract classes vs Interfaces: abstract classes can have implementation and state; interfaces define
contracts (C# supports default implementations since newer versions).
Sealed classes prevent inheritance. Partial classes split a class across files (helpful for generated code).
Constructors initialize instances; destructors/finalizers are rarely used — prefer IDisposable and Dispose for
deterministic cleanup.
Simple inheritance and overriding example.
class Animal {
public virtual void Speak(){ Console.WriteLine("... animal ..."); }
}
class Dog : Animal {
public override void Speak(){ Console.WriteLine("Woof!"); }
}
// Usage
var d = new Dog(); d.Speak();

Method Overloading vs Overriding

Overloading: same method name, different parameter lists within same class (compile-time).
Overriding: derived class provides specialized behavior for a virtual method defined in a base class (runtime
polymorphism).

Operator Overloading & Method Hiding

Operator overloading allows defining behavior for operators (e.g., +) for custom types. Use carefully to keep
code readable.
Method hiding (new keyword) hides a base class member with the same signature in derived class; typically
less preferred than virtual/override.

Interfaces & Generics

Interfaces declare contracts (methods/properties). Implement them in classes to promise behavior.


Generics provide type-safe reusable code. Use List<T>, Dictionary<TKey,TValue>, or create your own
generic classes/methods.
Constraints limit generic types (e.g., where T : class, where T : new(), where T : BaseType).
Generic interface and implementation.
public interface IRepository<T> { void Add(T item); T Get(int id); }
public class Repo<T> : IRepository<T> where T: class, new() {
public void Add(T item) { /*...*/ }
public T Get(int id) => new T();
}

Properties, Indexers, Auto-implemented properties

Properties wrap fields and provide a clean way to read/write values (get/set). Auto-implemented properties
are shorthand.
Indexers let an object be indexed like an array (e.g., myCollection[0]).
Auto-implemented property example.
public class Person { public string Name { get; set; } public int Age { get; private set; } }

Extension Methods & Anonymous Types

Extension methods let you add methods to existing types without modifying them. Place them in static
classes with 'this' parameter.
Anonymous types let you create lightweight objects without defining a class (useful in LINQ projections).
Extension method example.
public static class StringExtensions { public static bool IsCapitalized(this string s) { if (string.IsNullOrEmpty
return false; return char.IsUpper(s[0]); } }
// Usage: "Hello".IsCapitalized()

Evaluating Regular Expressions in C#

Use System.Text.RegularExpressions.Regex. Regular expressions are useful for pattern matching (email,
phone, validation).
Common methods: Regex.IsMatch, Regex.Match, Regex.Matches, Regex.Replace.
Email validation using Regex.IsMatch.
using System.Text.RegularExpressions;
bool valid = Regex.IsMatch("[email protected]", @"^\S+@\S+\.\S+$");

Exception Handling

Use try { } catch(Exception ex) { } finally { } to handle errors. Catch specific exceptions before general ones.
InnerException stores the original exception when wrapping. Throw helps re-throw exceptions; use throw; to
preserve stack trace.
Create custom exceptions by inheriting from Exception for domain-specific errors.
Try-catch-finally example.
try {
int x = int.Parse("notanumber");
} catch (FormatException ex) {
Console.WriteLine("Input was not a number: " + ex.Message);
} finally {
// cleanup
}
Garbage Collection in C#

The .NET GC automatically reclaims unused memory. Objects are allocated on the heap and GC runs
periodically to free memory.
Finalize (~ClassName) is non-deterministic. Implement IDisposable and Dispose for deterministic cleanup
(e.g., file handles).
Use 'using' statement to ensure Dispose is called automatically for IDisposable objects.
Using ensures Dispose is called.
using (var fs = System.IO.File.OpenRead("file.txt")) {
// use file
}

Collections & Generics (Deeper)

System.Collections (non-generic) and System.Collections.Generic (generic) namespaces provide collection


types.
Common collections: List<T>, Dictionary<TKey,TValue>, Queue<T>, Stack<T>, HashSet<T>,
LinkedList<T>.
Choose collections based on access patterns: List for index access, Dictionary for fast lookup by key, Queue
for FIFO, Stack for LIFO.
List and Dictionary examples.
var list = new List<int>{1,2,3};
var dict = new Dictionary<string,int>{{"a",1},{"b",2}};
if (dict.TryGetValue("a", out int v)){ Console.WriteLine(v); }

Creating and Using Generic Classes, Methods, Delegates

Generics help create reusable, type-safe code. Delegates represent references to methods (function
pointers). Use Action<T>/Func<T> for common cases.
Events are built on top of delegates for publish/subscribe patterns.
Func example for a delegate.
Func<int,int,int> add = (a,b) => a+b; Console.WriteLine(add(2,3));

IIS Publishing & Cross-Platform Deployments

Publish .NET Core apps using 'dotnet publish' and deploy to Windows IIS, Linux nginx, or Docker. Use the
appropriate hosting bundle or container base image.
For microservices, containerization (Docker) and orchestration (Kubernetes) are common practices.

Microservices using .NET Core

Microservices break an application into smaller services communicating over HTTP, gRPC, message
queues. .NET Core is suitable because of light-weight containers and high performance.
Consider API gateways, service discovery, tracing, resiliency (retry/circuit-breaker).

What is .NET Framework vs .NET Core (Comparison)

.NET Framework: Windows-only, mature for desktop and older web apps. .NET Core (now referred as .NET
5/6/7+) is cross-platform, modern, and recommended for new apps.
Use .NET Core for cross-platform and containerized workloads; use .NET Framework if you have legacy
Windows-only dependencies.
Sample: Small Console App (Complete Example)

This example shows a simple console app that demonstrates parsing, error handling, and a tiny class.
Console app that reads input, parses safely, and uses a helper class.
using System;
using System.Text;
class Program {
static void Main(){
Console.WriteLine("Enter a number:");
string input = Console.ReadLine();
if (!int.TryParse(input, out int n)){
Console.WriteLine("Invalid number.");
return;
}
var calc = new Calculator();
Console.WriteLine($"{n} squared is {calc.Square(n)}");
}
}
class Calculator {
public int Square(int x) => x*x;
}

Next Steps and Resources

Practice these topics by building small projects: a REST API, a console utility, and a simple WPF or Blazor
UI.
If you want, I can produce an expanded PDF focusing in-depth on any of these sections (with more
examples and exercises). Tell me which sections to expand.

You might also like