0% found this document useful (0 votes)
9 views22 pages

C# and .NET Overview: Key Concepts

C# is a modern, object-oriented programming language developed by Microsoft, used for various applications including desktop, web, mobile, and games. .NET is a developer platform created by Microsoft that provides tools and libraries for building applications, featuring components like the CLR for code execution and a class library for various functionalities. The document also covers the basic structure of a C# program, data types, operators, string methods, conditional statements, loops, and methods.

Uploaded by

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

C# and .NET Overview: Key Concepts

C# is a modern, object-oriented programming language developed by Microsoft, used for various applications including desktop, web, mobile, and games. .NET is a developer platform created by Microsoft that provides tools and libraries for building applications, featuring components like the CLR for code execution and a class library for various functionalities. The document also covers the basic structure of a C# program, data types, operators, string methods, conditional statements, loops, and methods.

Uploaded by

245121735167
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is C#?

is a modern, object-oriented programming language developed by Microsoft. It is strongly typed


(every variable must have a data type.).

Where C# is used:

 Desktop applications (Windows)


 Web applications ([Link])
 Mobile apps (Xamarin / MAUI)
 Games (Unity)

What is .NET?

.NET is a developer platform / framework created by Microsoft. It is used to build and run
applications. .NET being open source means its code is publicly available, which improves
transparency, performance, and cross-platform support. Works on Windows, Linux, macOS.

A framework is a collection of tools, libraries, and rules that provides a base so we don’t have to
write everything from scratch.

.NET provides (major components):

1. CLR (Common Language Runtime) (execution engine) is the runtime that executes the
code.
→ Executes code, handles memory, garbage collection, security, thread management
(parallel execution).

2. Class Library: provides a set of API s (reading and writing files, connecting to database) and
types for Strings, dates, numbers.
→ Ready-made classes for file handling, database, collections, networking, etc.

How C# and .NET Work Together:

C# Code → Compiled → IL (Intermediate Language) complied code is stored in assemblies (.exe file
extension)

IL → Executed by CLR → Output (when an app runs then CLR take this assembly and uses a JIT – just
in time compiler to execute into machine code that can run in specific computer).

Example: Console. WriteLine("Hello");

Console class comes from .NET library and Execution handled by CLR.
BASIC STRUCTURE OF A C# PROGRAM:

using System;

namespace MyApplication

class Program

static void Main(string[] args)

[Link]("Hello World");

 using System; -Using System allows access to predefined classes such as Console for input
and output operations

System is a built-in namespace in C#. It contains ready-made classes like: Console, Math, String.

using allows us to use those classes without writing full names.

 namespace MyApplication: A namespace is a container that groups related classes


together. It helps to Organize code, Avoid name conflicts in large applications.

You can have multiple namespaces, but one class belongs to one namespace.

 class Program: class is a blueprint. It contains Variables (data), Methods (functions).

everything runs inside a class.

 static void Main(string[] args): Main() is the entry point of a C# program.

Program execution always starts from Main.

 [Link]("Hello World");

Prints output to the console. WriteLine prints and moves cursor to next line.

Program starts CLR looks for Main ()Main executes statementProgram ends
Value Types (Stored in Stack Memory):

These hold the actual data, not references.

Type Example Notes

Int int a = 5; Integer -2 bytes

Long long c=23456; Long- 8 bytes

float float f = 3.5f; Needs f suffix -4 bytes

double double d = 3.5; Bigdeci by default -8 bytes

char char c = 'A'; Single character -2 bytes

string string s = "Hi"; Text -2 bytes per character

bool bool b = true; True/False – 1 byte

var var x = 10; Type inferred automatically

Reference Types (Stored in Heap Memory)

These store the address/location of data, not the data itself.

Type Description

string Text / collection of characters "Hello"

object Base type for all data types (Parent of all types)

dynamic Can store any type; type-checking happens at runtime

Arrays int [] numbers = {1,2,3};

Classes & Interfaces User-defined reference types

C# Typecasting: converting one data type into another.

 Implicit Casting (Automatic): Small → Big (No data loss)

Char -> byte → short → int → long → float → double → decimal

 Explicit Casting (Manual): Big → Small (Possible data loss)

double x = 58.48; // double is stored in int

int y = (int)x; // Decimal part removed

[Link](y); // Output: 58

Why double → float needs explicit cast?


because double (8 bytes) is bigger than float (4 bytes).
Converting large → small may cause data loss, so the programmer must confirm it manually.

double d = 47.392857;

float f = (float)d; // Explicit typecasting

[Link](f);

error occurs: "Cannot implicitly convert from double to float".

 Typecasting using Methods: C# provides built-in methods in Convert & Parse.

Method Converts To

Convert.ToInt32() int

[Link]() double

[Link]() float

[Link]() bool

[Link]() string

Ex: string val = "123"; double d = 47.39;

int num = Convert.ToInt32(val); string s = [Link](d);

Using Parse () Method: Works only for string → numeric.

string price = "500";

int p = [Link](price); // If string is not numeric → exception/error.

 C# OPERATORS :

Operators are special symbols used to perform operations on variables and values.

Arithmetic Operators: Used for mathematical calculations.

1. Assignment Operators: Used to assign values to variables.

[Link] / Comparison Operators: Used to compare two values → returns true/false.

[Link] Operators: Used with boolean conditions.

[Link] Operators: Works on a single operand.

[Link] Operator: Shortcut for if/else.

[Link] Operators: Used for bit-level operations

7. Assignment Operators: Used to assign values to variables.

Operator Precedence (Order of Execution):


() ++, -- *, /, % +, - <, >, <=, >= ==, != && || ?:

Assignment Operators:

Operator Meaning Example

+ Addition a+b

- Subtraction a-b

* Multiplication a*b

/ Division a/b

% Modulus (Remainder) 10 % 3 = 1

Relational / Comparison Operators:

Operator Meaning

== Equal to

!= Not equal to

> Greater than

< Less than

>= Greater or equal

<= Less or equal

. Assignment Operators

Operator Meaning

= Assign

+= Add & assign

-= Subtract & assign

*= Multiply & assign

/= Divide & assign

%= Modulus & assign

Logical Operators:

Operator Meaning Returns true if

&& Logical AND Both conditions are true


Operator Meaning Returns true if

|| Logical OR Any one condition is true

! Logical NOT Reverses boolean value

Unary Operators

Operator Meaning

++ Increment (add 1)

-- Decrement (subtract 1)

+a Positive value

-a Negative value

Ternary Operator

condition? value_if_true : value_if_false;

Bitwise Operators

Operator Meaning

& AND

` `

^ XOR

~ NOT

<< Left Shift

>> Right Shift

✔ Arithmetic → + - * / %
✔ Assignment → += -= *= /=
✔ Relational → returns true/false
✔ Logical → used with conditions
✔ Ternary → short if/else
✔ Unary → ++ --
✔ Precedence → () , *,/ then +,-

Special Operators:

Operator Use

typeof() Returns data type

Sizeof () Size of datatype in bytes


Operator Use

is Check object type

as Safe type conversion

new Create object

?: Ternary operator

[] Indexing arrays

Math Class in C#:

The Math class belongs to the System namespace and provides built-in mathematical methods,
constants, and calculations.

Math class is static → You don't create an object. You call methods directly using:

[Link]();

Method Description Example

[Link](x) Absolute value (positive result) [Link](-10) → 10

[Link](a, b) Returns largest value [Link](10,20) → 20

[Link](a, b) Returns smallest value [Link](10,20) → 10

[Link](x) Square root [Link](25) → 5

[Link](x, y) x raised to the power y [Link](2,3) → 8

[Link](x) Rounds to nearest whole number [Link](4.6) → 5

[Link](x) Rounds down [Link](4.9) → 4

[Link](x) Rounds up [Link](4.1) → 5

[Link](x) -1 (negative), 0, +1 (positive) [Link](-5) → -1

[Link](x) Removes decimals, no rounding [Link](3.99) → 3

Constant Description

[Link] 3.141592653589793...

Math.E 2.718281828459045... (Euler’s constant)


✔ Default angle unit: Radians
✔ Round (), Floor (), Ceiling () behave differently
✔ Pow () always returns double

STRING METHODS IN C#:

Strings are reference types stored in [Link] class and they are immutable (cannot be
changed once created).

Basic String Methods:

Method Description Example

Length Returns number of characters "Hello".Length → 5

ToUpper () Converts to uppercase "hi".ToUpper() → "HI"

ToLower () Converts to lowercase "HI".ToLower() → "hi"

Trim () Removes spaces (start & end) " hi ".Trim() → "hi"

TrimStart () Removes leading spaces " hi".TrimStart()

TrimEnd () Removes ending spaces "hi ".TrimEnd()

Searching & Checking Methods:

Method Description Example

Contains("x") Check if text exists "Hello".Contains ("He") → true

StartsWith("x") Check if string begins with text "World".StartsWith("Wo") → true

EndsWith("x") Check ending "World".EndsWith("ld") → true

IndexOf("x") Returns position "apple".IndexOf("p") → 1

LastIndexOf("x") Last position of character "apple".LastIndexOf("p") → 2

Substring Methods:

Method Description Example

Substring(start) From index to end "Likitha".Substring(2) → "kitha"

Substring(start, length) Returns portion of string "Likitha".Substring(0,3) → "Lik"


Method Description Example

Replace & Remove:

Method Description Example

Replace(a,b) Replace text/char "Hello".Replace("H","Y") → "Yello"

Remove(start) Remove from index to end "Laptop".Remove(3) → "Lap"

Remove(start,count) Remove specific portion "Laptop".Remove(1,3) → "Lop"

Splitting & Joining:

Method Description Example

Split() Breaks string into array "A,B,C".Split(',') → ["A","B","C"]

Join() Combines array into string [Link]("-", arr)

Comparing Strings:

Method Description

Equals() Checks if strings are equal (case sensitive)

Compare() Returns 0 if equal, -1/+1 if not

CompareTo() Same as Compare but used with objects

Insert & Pad Methods:

Method Description Example

Insert () Insert text at a position "Car".Insert (0,"New ") → "New Car"

PadLeft(n) Add spaces before text "Hi".PadLeft (5) → " Hi"

PadRight(n) Add spaces after text "Hi".PadRight (5) → "Hi "

For editable strings repeatedly, use StringBuilder.

using [Link];

StringBuilder sb = new StringBuilder("Hello");

[Link](" World");
[Link]("World", "C#");

[Link]([Link]());

String Interpolation in C#:

String Interpolation is a feature that allows you to insert variables directly inside a string using the $
symbol.

string name = "Likitha";

int age = 21;

[Link]($"My name is {name} and I am {age} years old.");

//My name is Likitha and I am 21 years old.

Conditional Statements in C#:

Conditional statements are used to make decisions in a program based on conditions.


They execute certain code only if a condition is true.

 if Statement: Executes code only when condition is true.

if (condition)

// code to execute

 if - else Statement: Runs one block if true, otherwise another block.

int age = 16;

if (age >= 18) {

[Link]("Adult");

else{

[Link]("Minor");

 if - else if - else Ladder: Used when there are multiple conditions to check.

int marks = 85;

if (marks >= 90) {

[Link]("Grade A");

}
else if (marks >= 75) {

[Link]("Grade B");

else if (marks >= 50) {

[Link]("Grade C");

else {

[Link]("Fail");

 Nested if (if inside another if): Used when conditions depend on other conditions.

int age = 20;

bool hasID = true;

if (age >= 18) {

if (hasID)

[Link]("Entry Allowed");

else

[Link]("ID Required");

else {

[Link]("Entry Denied");

Conditions in if must return true/false


✔ Strings must be compared using == or .Equals()
✔ || = any one condition true, && = both must be true
✔ Ternary operator is best for short conditions

If → single check
If-else → two choices
Else if → multiple conditions
Nested if → decision inside decision
Ternary → short form

Switch Case in C#: The switch statement is used to execute one block of code from multiple options
based on a matching value. It works like an alternative to multiple if-else-if statements.
switch(expression)

case value1:

// code to execute

break;

case value2:

// code to execute

break;

...

default:

// code to execute if no case matches

break;

Many conditions checking same variable best choice to use Switch.

Switch Expressions (Modern C#):

string grade = "A";

string result = grade switch

"A" => "Excellent",

"B" => "Good",


"C" => "Average",

_ => "Invalid Grade"

};

[Link](result);

Loops in C#: Loops are used to execute a block of code repeatedly as long as a condition is true.

 for Loop: Used when the number of iterations is known.

for (initialization; condition; increment/decrement)

// code to execute

Initialization runs once  Condition checked  If true → code executes  Increment/Decrement


applies  Repeats until condition becomes false.

 while Loop: Used when the number of iterations is unknown; depends on condition.

while(condition) int i = 1;

{ while (i <= 5) {

// code [Link](i); i++;

} }

Condition is checked before running the loop.

If condition is false initially → loop will not run.

 do-while Loop: Similar to while, but executes at least once, even if the condition is false.

do

// code

} while(condition);

Code executes first → condition checked later.


Guaranteed one-time execution.

 foreach Loop: Used to iterate through a collection (arrays, lists, strings, etc.)

Best for reading values, not modifying the index.

Syntax:

foreach (datatype variable in collection)

// code

Example:

string [] colors = { "Red", "Blue", "Green" };

foreach (string c in colors)

[Link](c);

Jump Statements in Loops:

Keyword Description

break Stops the loop immediately

continue Skips current iteration and continues with next

goto Jumps to a labelled section (not recommended generally)

Methods in C#: A method is a block of code that performs a task. It helps achieve reusability,
readability, and modular programming.

Syntax:

returnType MethodName(parameters)

// code to execute

Why do we use Methods?


 Avoids rewriting code

 Makes program modular and organized

 Improves readability and debugging

 Supports code reusability

Type Description

Void Method Performs an action but does not return a value

Return Type Method Returns a value to the caller

Parameter Method Accepts input values

No Parameter Method Does not accept inputs

Static Method Belongs to class; call by class name

Instance (Non-static) Method Belongs to object; call through object

 Void Method:

void ShowMessage ()

[Link]("Hello World!");

To call a method: ShowMessage ();

 Method with Return Type:

int Add ()

return 10 + 20;

To call a method:

int result = Add ();

[Link](result);
 Method with Parameters:

int Add (int a, int b){

return a + b;

To call a method:

[Link](Add (5, 10));

Method Overloading: Same method name, different parameters (count/datatype/order).

Passing Parameters:

Type Description Example

Pass by Value Sends value only (default) Add(a)

ref Passes reference (must be initialized) Add (ref a)

out Outputs value (no need to initialize) Add (out a)

params Accepts multiple arguments as array Sum (params int [] numbers)

int Sum (params int [] numbers)

int total = 0;

foreach (int n in numbers)

total += n;

return total;

[Link](Sum (10, 20, 30, 40));

Modifier Usage

public Accessible anywhere

private Accessible within class only

protected Within class + inherited class

internal Within the same project/assembly

protected internal mix of protected + internal

OOPS:
Class = logical structure, Object = physical/real instance

Class does not occupy memory until object is created. Object allocates memory in the heap.

Classes: is a blueprint/template that defines properties (variables) and behaviors (methods).

class ClassName

// variables / fields

// methods

Objects: is an instance of a class — created in memory using the class structure.

ClassName obj = new ClassName ();

Constructors in C#:

A constructor is a special method that has the same name as the class

Does not have a return type (not even void), Automatically executes when object is created.

Types of Constructors:

Type Meaning

Default Constructor No parameters, auto-created if not defined

Parameterized Constructor Accepts values to initialize data

Copy Constructor (Manually created) Copies values from another object

Static Constructor Runs once per class, for static data initialization

Default Constructor:

class Person

public Person ()

[Link]("Default constructor executed");

Parameterized Constructor:

class Person

{
string name;

int age;

public Person (string n, int a)

name = n;

age = a;

Copy Constructor:

class Person

string name;

public Person (string n)

name = n;

public Person (Person obj)

name = [Link];

Static Constructor:

No parameters allowed in static constructor

Executes once before accessing class or object

Cannot be called manually

class Test

static Test ()

[Link]("Static constructor runs once only");


}

Encapsulation: Encapsulation = Binding data + methods to protect data.

Achieved using: private variables (Protects data) and public getters/setters (Controlled access
through methods)

class Bank

private double balance; // restricted

public void SetBalance (double amt)

balance = amt;

public double GetBalance ()

return balance;

Inheritance: Inheritance allows a class (child) to acquire properties/methods of another class


(parent).

Syntax:

class Parent { }

class Child: Parent { }

Single Inheritance:

class A {

public void showA () {

[Link]("A");

}}

class B: A {

public void showB ()


{[Link]("B");

}}

Multi-Level Inheritance:

class A { }

class B: A { }

class C: B { }

C# does NOT allow multiple inheritance with classes. But supported through Interfaces.

Polymorphism: Same name, different behavior.

Type How Keyword

Compile-time Method Overloading same name + different params

Run-time Method Overriding virtual + override

Method Overloading:

class Test

void show (int a) { }

void show (string b) { }

Method Overriding:

class Parent

public virtual void display () {

[Link]("Parent");

}}

class Child: Parent

public override void display () {

[Link]("Child");

}}

Abstraction: Hiding internal details and showing only essential features.


abstract class Animal

public abstract void sound (); // no body

class Dog: Animal

public override void sound ()

[Link]("Bark");

Cannot create object of abstract class.


Must override abstract methods in child class.

Interface in C#:

Interface is a contract — only declaration, no implementation inside it.

interface IAnimal

void sound (); // like abstract method

class Dog: IAnimal

public void sound()

[Link]("Dog Barks");

}
Abstract Class Interface

Can have abstract & normal methods Only abstract methods (default)

Can have constructors No constructors

Supports access modifiers No access modifiers

Inheritance: Single Inheritance: Multiple allowed

Partial abstraction 100% abstraction

You might also like