C Sharp Tutorials
- Get link
- X
- Other Apps
Overview
Topic | Description/Answer |
Overview | - Introduction to .NET Framework - .NET Framework (Basic Architecture and Component Stack) - Managed vs Unmanaged Code in .NET |
Managed vs Unmanaged Code | - Managed code is controlled by CLR - Unmanaged code runs directly by the operating system |
CIL or MSIL | - Common Intermediate Language - Microsoft Intermediate Language - Intermediate code produced by .NET compiler |
.NET Framework Class Library (FCL) | - Comprehensive, object-oriented collection of reusable types - Classes, interfaces, and value types used to build applications |
Introduction to C# | - Modern, general-purpose, object-oriented programming language |
Setting up the Environment in C# | - Use of integrated development environments (IDEs) like Visual Studio |
How to Install and Setup Visual Studio for C#? | - Download from Microsoft's official site - Follow installation guide - Set up a new project |
Evolution of C# | - Development and growth of C# over time |
Hello World in C# | - Basic C# program to print "Hello, World!" to console |
How to Execute C# Program on cmd? | - Use csc to compile - Run with .exe file generated |
Main Method | - Entry point of a C# application - Every C# program must have it |
Getting Familiar With Visual Studio | - Explore its features, debugging tools, and user interface |
Common Language Runtime(CLR) | - Heart of .NET Framework - Provides memory management, security, and exception handling |
Architecture of Common Language Runtime (CLR) | - How CLR manages code execution, memory, etc. |
JIT(Just-In-Time) Compiler | - Converts intermediate language (CIL) to machine code at runtime |
Garbage Collection | - Automatic memory management of CLR - Releases memory occupied by unused objects |
Windows Form Applications | - GUI-based apps in .NET - Allows for event-driven programming |
C vs C# | - Differences in syntax, memory management, etc. |
C++ vs C# | - C++ is lower-level with manual memory management, while C# is higher-level with garbage collection |
Java vs C# | - Similar syntax but different libraries, runtime environments, etc. |
Python vs C# | - Python is interpreted, dynamically-typed while C# is compiled, statically-typed |
Interesting Facts about C# | - Historical, unique, or lesser-known information about C# |
Type System Unification in C# .NET | - Ensures that all types, whether value or reference, inherit from System.Object |
Fundamentals
Topic | Description/Answer | C# Code Example |
Identifiers | - Names given to elements in a program like variables, functions, etc. - Must start with a letter or underscore | int myIdentifier = 5; |
Data Types | - Defines the type of data a variable can store | int num = 10; string text = "Hello"; |
Variables | - Used to store data for processing | double myVariable = 3.14; |
Types of Variables | - Different variable types based on data stored and scope | int globalVar; void MyFunc() { int localVar; } |
Implicitly Typed Local Variables – var | - Compiler determines the type | var myVar = "Hello"; |
Dynamic Type in C# | - Type is resolved at runtime | dynamic myDynamic = 100; |
var vs dynamic | - var is statically-typed but determined at compile-time - dynamic is determined at runtime | var myVar = 10; dynamic myDynamic = "C#"; |
Binary Literals and Digit Separators | - Represents data in binary and improves readability | int binary = 0b1011_1010; |
Scope of Variables | - Where a variable can be accessed | { int localVar; } // Local to block |
Access Modifiers | - Determines visibility of a class, method, or variable | public int myNum; private string myStr; |
Constants or Literals | - Immutable values | const double PI = 3.14; |
Operators | - Symbols used to perform operations | int result = 5 + 10; |
Command Line Arguments | - Arguments passed during program execution | static void Main(string[] args) { } |
Boxing and Unboxing | - Boxing: converting value type to reference type - Unboxing: vice-versa | object boxed = 10; int unboxed = (int)boxed; |
Boxing vs UnBoxing | - Boxing involves heap allocation - Unboxing retrieves value | // As above |
Params in C# | - Allows passing variable number of arguments | void ShowValues(params int[] values) { } |
Comments in C# | - Used to describe or comment out code | // Single line comment /* Multi-line comment */ |
Type Casting or Type Conversion | - Converting one data type to another | int myInt = (int)10.5; |
Enumeration in C# | - Named constants of underlying integral data type | enum Days { Sun, Mon, Tue, Wed }; |
Properties in C# | - Members of a class that provide a flexible mechanism to read, write or compute private fields | public int MyProperty { get; set; } |
Nullable Types | - Types which can represent a normal value or a null value | int? nullableInt = null; |
Structures | - Value type data structure which can contain members of different data types | struct Point { public int x, y; } |
Important Keywords
Topic | Description/Answer | C# Code Example |
as Keyword | - Used for type conversions - If conversion fails, returns null instead of an exception | object obj = "Hello"; string str = obj as string; |
is Keyword | - Checks if the object matches the given type | object obj = "Hello"; if (obj is string) { } |
Is vs As operator keyword | - is: checks type and returns boolean - as: performs type conversion or returns null | object obj = 5; bool check = obj is int; int? num = obj as int?; |
static keyword | - Denotes a member that belongs to the type itself, not to an instance | static int count; |
typeof Keyword | - Gets the System.Type of an object | Type type = typeof(string); |
Difference between readonly and const keyword | - const: Compile-time constant, cannot be changed - readonly: Runtime constant, set in constructor only | const double PI = 3.14; readonly int myReadonlyVar; |
ref keyword | - Indicates reference is passed, not value, allowing function to modify original data | void MyMethod(ref int x) { x = 10; } int num = 5; MyMethod(ref num); |
Control Statements
Topic | Description/Answer | C# Code Example |
Decision-Making Statements | - Allow you to make decisions and execute a particular block of code based on certain conditions | if (x > 10) { Console.WriteLine("Greater than 10"); } else { Console.WriteLine("Less than or equal to 10"); } |
Switch Statement | - Allows a variable to be tested for equality against multiple cases | switch (x) { case 1: Console.WriteLine("One"); break; case 2: Console.WriteLine("Two"); break; default: Console.WriteLine("Other"); } |
Loops | - Execute a block of code multiple times based on a condition or set of conditions | while (x < 5) { Console.WriteLine(x); x++; } |
Foreach Loop | - Iterates over items in a collection or array | string[] names = { "Alice", "Bob", "Charlie" }; foreach (string name in names) { Console.WriteLine(name); } |
Jump Statements | - Allow you to jump to another point in the program | // see below for individual jump statements |
Break (Jump Statement) | - Used to exit from a loop or switch statement | for (int i = 0; i < 10; i++) { if (i == 5) break; Console.WriteLine(i); } |
Continue (Jump Statement) | - Skips the current iteration of a loop and continues with the next | for (int i = 0; i < 10; i++) { if (i == 5) continue; Console.WriteLine(i); } |
Goto (Jump Statement) | - Allows you to jump to a labeled statement in your program | start: Console.WriteLine("Start"); goto end; Console.WriteLine("This won't get printed"); end: Console.WriteLine("End"); |
Return (Jump Statement) | - Exits from a method and optionally returns a value | int Add(int a, int b) { return a + b; } |
Throw (Jump Statement) | - Used to indicate an exception | if (x < 0) { throw new ArgumentOutOfRangeException(); } |
OOP Concepts
Topic | Description/Answer | C# Code Example |
Class and Object | - Class: blueprint for creating objects - Object: instance of a class | class MyClass { } MyClass obj = new MyClass(); |
Nested Classes | - Class defined inside another class | class Outer { class Nested { } } |
Difference between Class and Structure | - Class: reference type - Structure: value type | class MyClass { } struct MyStruct { } |
Early and Late Binding | - Early: type known at compile time - Late: type known at runtime | // Early int x = 10; // Late object obj = "Hello"; |
Overloading of Constructors | - Multiple constructors with different parameters | class MyClass { public MyClass() { } public MyClass(int x) { } } |
Inheritance in C# | - Allows a class to inherit properties and methods from another class | class Base { } class Derived : Base { } |
Encapsulation in C# | - Bundling data and methods that operate on that data within a single unit | class Capsule { private int data; public int GetData() { return data; } } |
Abstraction in C# | - Hiding complex implementation and exposing only necessary parts | abstract class AbstractBase { public abstract void MyMethod(); } |
this keyword | - Refers to the current instance of the class | class MyClass { int x; public MyClass(int x) { this.x = x; } } |
Static Class | - Cannot be instantiated and its members can be accessed directly | static class MyStaticClass { public static void MyMethod() { } } |
Partial Classes | - Allows splitting a class definition across multiple files | partial class MyPartialClass { } |
Shallow Copy and Deep Copy | - Shallow: references to objects - Deep: copies objects | // Shallow MyClass obj2 = obj1; // Deep requires manual or specialized methods |
Different ways to create an Object | - Using new keyword, reflection, etc. | MyClass obj1 = new MyClass(); object obj2 = Activator.CreateInstance(typeof(MyClass)); |
Object and Collection Initializer | - Allows you to initialize objects or collections at declaration time | var person = new { Name = "John", Age = 25 }; |
Accessing structure’s elements using Pointers | - Pointers can be used with structures in unsafe context | unsafe { MyStruct* ptr = &myStruct; ptr->x = 10; } |
Methods | - Blocks of code that perform a specific task and can be called upon | void MyMethod() { Console.WriteLine("Hello"); } |
Methods
Topic | Description/Answer | C# Code Example |
Methods | - Blocks of code designed to perform a particular task | void Greet() { Console.WriteLine("Hello"); } |
Method Overloading | - Defining multiple methods in a class with the same name but different parameters | void Display() { } void Display(int x) { } |
Method Returning an Object | - Method that returns an instance of a class | MyClass CreateObject() { return new MyClass(); } |
Method Parameters | - Inputs to the method to influence its behavior | void Add(int a, int b) { } |
Runtime(Dynamic) Polymorphism | - Achieved through method overriding | class Base { virtual void Show() { } } class Derived : Base { override void Show() { } } |
Method Overriding | - Redefining a base class method in a derived class | class Base { virtual void Show() { } } class Derived : Base { override void Show() { } } |
Method Hiding | - Hiding a base class method using new keyword in derived class | class Base { void Show() { } } class Derived : Base { new void Show() { } } |
Method Overriding vs Method Hiding | - Overriding: Redefines & uses base method - Hiding: Uses new method, hides base method | // See above examples for Overriding and Hiding |
Optional Parameters | - Parameters that have default values | void Display(string msg = "Hello") { } |
Different ways to make Method Parameter Optional | - Using default values - Using params keyword | void Show(int x, params int[] nums) { } |
Out Parameters with examples | - Method returns data in parameters marked with out | void GetDimensions(out int width, out int height) { width = 10; height = 20; } |
Difference between Ref and Out keywords | - ref: input/output - out: just output | void MyMethod(ref int a, out int b) { b = a; } |
Anonymous Method | - Method without a name, used with delegates | delegate void Display(); Display show = delegate { Console.WriteLine("Hello"); }; |
Partial Methods | - Can have a declaration in one part of a partial class & definition in another | partial void MyPartialMethod(); |
Extension Method | - Add methods to existing type without modifying it | public static void ExtendMethod(this MyClass obj) { } |
Local Function | - Function declared within another method | void MyMethod() { void LocalFunc() { } LocalFunc(); } |
Delegates
Topic | Description/Answer | C# Code Example |
Delegates | - Type-safe function pointers - Allows methods to be passed as parameters | delegate void MyDelegate(); |
Delegate Usage | - Assigning a method to a delegate and invoking it | MyDelegate del = SomeMethod; del(); |
Predicate Delegate | - Represents method containing conditions that return a boolean | Predicate<int> isEven = x => x % 2 == 0; |
Predicate Usage | - Using the Predicate delegate to test conditions | bool result = isEven(4); |
Action Delegate | - Represents a method with a void return type and optional parameters | Action<string> display = msg => Console.WriteLine(msg); |
Action Usage | - Using the Action delegate to perform an operation | display("Hello, World!"); |
Func Delegate | - Represents a method that can return a value and can have zero to 16 input parameters | Func<int, int, int> add = (a, b) => a + b; |
Func Usage | - Using the Func delegate to compute and return a value | int sum = add(5, 3); |
Multicast Delegates | - Delegates that can have references to more than one function | MyDelegate del1 = Method1; MyDelegate del2 = Method2; MyDelegate delCombined = del1 + del2; |
Multicast Invocation | - Invoking a multicast delegate to execute multiple methods | delCombined(); |
Delegate Combination | - Combining multiple delegate instances | MyDelegate del3 = del1 + del2; |
Delegate Removal | - Removing a method reference from a multicast delegate | del3 -= del1; |
Anonymous Delegate | - Delegate instance without a named method | MyDelegate anonDel = delegate { Console.WriteLine("Anonymous Delegate"); }; |
Action with Multiple Parameters | - Action delegate taking more than one parameter | Action<int, int> displaySum = (a, b) => Console.WriteLine(a + b); |
Func with Multiple Parameters | - Func delegate taking multiple inputs and returning a result | Func<int, int, string> formatSum = (a, b) => $"Sum: {a + b}"; |
Delegate as Parameter | - Passing a delegate as a method parameter | void InvokeDelegate(MyDelegate del) { del(); } |
Delegate Return | - Method that returns a delegate | MyDelegate GetDelegate() { return SomeMethod; } |
Generic Delegates | - Delegates that can operate on generic types | delegate T MyGenericDelegate<T>(T param); |
Predicate with Complex Types | - Using Predicate delegate with complex data types | Predicate<Person> isAdult = person => person.Age >= 18; |
Chaining Func Delegates | - Chaining multiple Func delegates together | Func<int, int> multiplyBy2 = x => x * 2; Func<int, int> add3 = x => x + 3; var result = add3(multiplyBy2(4)); |
Constructors
Topic | Description/Answer | C# Code Example |
Constructors in C# | - Special methods in a class - Automatically called when an object is created - No return type | public MyClass() { } |
Default Constructor | - Constructor without parameters - Automatically provided if no other constructor is defined | public MyClass() { } |
Copy Constructor | - Constructor that copies values of one object into another object | public MyClass(MyClass obj) { this.value = obj.value; } |
Private Constructor | - Prevents creating instances from outside the class | private MyClass() { } |
Constructor Overloading | - Defining multiple constructors with different sets of parameters | public MyClass() { } public MyClass(int x) { } |
Static Constructors vs Non-Static Constructors | - Static: Runs once per type - Non-Static: Runs once per instance | static MyClass() { } public MyClass() { } |
Invoking an overloaded constructor using this keyword | - Calls another constructor from a constructor within the same class | public MyClass() : this(10) { } public MyClass(int x) { } |
Destructors | - Used for cleanup - Cannot be called directly or defined with parameters - Called automatically by the CLR | ~MyClass() { //cleanup code } |
When to use a Default Constructor? | - Initialize default values - Ensure class can be instantiated without parameters | public MyClass() { value = 0; } |
Benefits of Private Constructor | - Restricts instantiation - Useful in singleton pattern | // Singleton pattern |
Purpose of Copy Constructor | - Duplicate an object - Ensure deep copy of objects | public MyClass(MyClass obj) { this.value = obj.value; } |
Using Multiple Constructors | - Different ways to create an object - Useful for different initialization scenarios | public MyClass(string name) { } public MyClass(int id) { } |
Static Constructor Timing | - Invoked only once before any instance or static members are accessed | static MyClass() { Console.WriteLine("Static Constructor"); } |
Non-Static Constructor Timing | - Invoked every time an instance of the class is created | public MyClass() { Console.WriteLine("Instance Constructor"); } |
How destructors work? | - Called automatically when object goes out of scope - Used for cleanup before garbage collection | ~MyClass() { Console.WriteLine("Destructor Called"); } |
Importance of Constructor Overloading | - Flexibility in object creation - Suitable initialization based on different requirements | public MyClass() { } public MyClass(int x, int y) { } |
Static Constructor Characteristics | - No access modifier - Only one static constructor allowed | static MyClass() { } |
Difference between Constructors & Destructors | - Constructors: initialize an object - Destructors: cleanup before garbage collection | public MyClass() { } ~MyClass() { } |
When is a Destructor called? | - Automatically, before garbage collector reclaims the object memory | ~MyClass() { Console.WriteLine("Destructor Called"); } |
Relationship between this keyword & constructors | - this refers to the current instance - Can be used to invoke other constructors within the same class | public MyClass() : this("Default") { } public MyClass(string name) { this.name = name; } |
Arrays
Topic | Description/Answer | C# Code Example |
Arrays | - Collection of items of the same type - Fixed size once created | int[] arr = new int[5]; |
Jagged Arrays | - Array of arrays - Different row sizes | int[][] jaggedArr = new int[3][]; |
Arrays of Strings | - Collection of string values | string[] strArray = { "Hello", "World" }; |
Using foreach loop in arrays | - Iterates over array elements | foreach(int num in arr) { Console.WriteLine(num); } |
Array Class | - Provides static methods for creating, manipulating, and querying arrays | Array.Clear(arr, 0, arr.Length); |
Sorting an Array | - Arranges elements in a sequence | Array.Sort(arr); |
Length of an Array | - Returns total number of elements in the array | int length = arr.Length; |
Array.BinarySearch() Method | - Searches for a value using binary search | int index = Array.BinarySearch(arr, 3); |
Check if two array objects are equal or not | - Determines if two arrays have identical elements | bool areEqual = Array.Equals(arr1, arr2); |
Number of elements in a specified dimension of an Array | - Gets the total elements in a specific dimension | int firstDimLength = arr.GetLength(0); |
LongLength property of an Array | - Returns the total number of elements (Long data type) | long length = arr.LongLength; |
Rank of an Array | - Determines the number of dimensions | int rank = arr.Rank; |
Passing Arrays as Arguments | - Arrays can be passed to methods as parameters | void PrintNumbers(int[] numbers) { } |
Implicitly Typed Arrays | - Array type inferred from the elements | var numbers = new[] { 1, 2, 3 }; |
Object and Dynamic Arrays | - Array of object or dynamic type | object[] objArray = { 1, "two", 3.0 }; |
Array IndexOutofRange Exception | - Thrown when accessing an index outside the bounds of the array | try { int x = arr[10]; } catch(IndexOutOfRangeException) { } |
Different ways to sort an array in descending order | - Use Array.Sort and then Array.Reverse - Use LINQ queries | Array.Sort(arr); Array.Reverse(arr); OR arr = arr.OrderByDescending(n => n).ToArray(); |
ArrayList
Topic | Description/Answer | C# Code Example |
What is ArrayList? | - Dynamic array - Can store any type of items - Automatically resizes | N/A |
How to create the ArrayList? | - Instantiate using the ArrayList class from System.Collections namespace | ArrayList myList = new ArrayList(); |
ArrayList Class | - Provides methods for manipulating dynamic collections | N/A |
Array vs ArrayList | Array: - Fixed size - Typed ArrayList: - Dynamic size - Can store any type | N/A |
Adding the elements to the end of the ArrayList | - Use Add method | myList.Add(100); |
Removing all the elements from the ArrayList | - Use Clear method | myList.Clear(); |
Removing a range of elements from the ArrayList | - Use RemoveRange method | myList.RemoveRange(0, 2); // Removes first two elements |
ArrayList to Array Conversion | - Use ToArray method | object[] arr = myList.ToArray(); |
Copying the entire ArrayList to a 1-D Array | - Use CopyTo method | myList.CopyTo(arr); |
Copying the entire ArrayList to 1-D Array starting at the specified index | - Specify the starting index in the CopyTo method | myList.CopyTo(arr, 2); // Starts copying from index 2 of the array |
Check if two ArrayList objects are equal | - Two ArrayLists are equal if they have the same elements in the same order | bool isEqual = ArrayList.Equals(myList1, myList2); |
String
Topic | Description/Answer | C# Code Example |
String | - Sequence of characters - Immutable | string str = "Hello"; |
Verbatim String Literal – @ | - Allows you to use special characters without escaping them - Useful for paths | string path = @"C:\Users\Name\Documents"; |
String Class | - Represents a string of text - Offers various methods to manipulate strings | string text = "OpenAI"; |
String Class Properties | - Properties to get information about the string content | int length = text.Length; |
How to use strings in switch statement | - You can use strings as cases in a switch statement | switch(text) { case "OpenAI": break; } |
StringBuilder in C# | - Represents a mutable string of characters - Good for string manipulations | StringBuilder sb = new StringBuilder("Hello"); |
String vs StringBuilder | String: - Immutable StringBuilder: - Mutable and efficient for string operations | N/A |
Length of the StringBuilder | - Gets the length of the current StringBuilder instance | int sbLength = sb.Length; |
Remove all characters from StringBuilder | - Clear the contents | sb.Clear(); |
Check if two StringBuilder objects are Equal | - Use Equals method - However, it checks for reference equality, not content equality | bool areEqual = sb1.Equals(sb2); |
Capacity of a StringBuilder | - Gets or sets the max number of characters this instance can hold without resizing | int capacity = sb.Capacity; |
Tuple
Topic | Description/Answer | C# Code Example |
What is Tuple in C#? | - Represents a data structure that has a specific number and sequence of elements | N/A |
Tuple Class | - Provides static methods for creating tuple objects | var t = Tuple.Create(1, "one"); |
Tuple<T1> Class | - Represents a 1-tuple or singleton | Tuple<int> single = new Tuple<int>(1); |
Tuple<T1,T2> Class | - Represents a 2-tuple or pair | Tuple<int, string> pair = new Tuple<int, string>(1, "one"); |
Tuple<T1,T2,T3> Class | - Represents a 3-tuple | Tuple<int, string, bool> tri = new Tuple<int, string, bool>(1, "one", true); |
Tuple<T1,T2,T3,T4> Class | - Represents a 4-tuple | Tuple<int, string, bool, double> quad = new Tuple<int, string, bool, double>(1, "one", true, 1.1); |
Tuple<T1,T2,T3,T4,T5> Class | - Represents a 5-tuple | Tuple<int, string, bool, double, char> quint = new Tuple<int, string, bool, double, char>(1, "one", true, 1.1, 'a'); |
Tuple<T1,T2,T3,T4,T5,T6> Class | - Represents a 6-tuple | Tuple<int, string, bool, double, char, long> sext = new Tuple<int, string, bool, double, char, long>(1, "one", true, 1.1, 'a', 100L); |
Tuple<T1,T2,T3,T4,T5,T6,T7> Class | - Represents a 7-tuple | Tuple<int, string, bool, double, char, long, decimal> sept = new Tuple<int, string, bool, double, char, long, decimal>(1, "one", true, 1.1, 'a', 100L, 1.01m); |
Tuple<T1,T2,T3,T4,T5,T6,T7,TRest> Class | - Represents a tuple with 7 elements and an additional generic type for the rest of the elements | var oct = new Tuple<int, string, bool, double, char, long, decimal, Tuple<int>>(1, "one", true, 1.1, 'a', 100L, 1.01m, new Tuple<int>(8)); |
ValueTuple
Topic | Description/Answer | C# Code Example |
What is ValueTuple in C#? | - Represents a value type tuple | N/A |
ValueTuple Struct | - Represents a value type tuple with no elements | ValueTuple emptyTuple = new ValueTuple(); |
ValueTuple <T1> Struct | - Represents a value type 1-tuple | (int) singleValueTuple = (1); |
ValueTuple <T1,T2> Struct | - Represents a value type 2-tuple | (int, string) pairValueTuple = (1, "one"); |
ValueTuple <T1,T2,T3> Struct | - Represents a value type 3-tuple | (int, string, bool) triValueTuple = (1, "one", true); |
ValueTuple <T1,T2,T3,T4> Struct | - Represents a value type 4-tuple | (int, string, bool, double) quadValueTuple = (1, "one", true, 1.1); |
ValueTuple <T1,T2,T3,T4,T5> Struct | - Represents a value type 5-tuple | (int, string, bool, double, char) quintValueTuple = (1, "one", true, 1.1, 'a'); |
ValueTuple <T1,T2,T3,T4,T5,T6> Struct | - Represents a value type 6-tuple | (int, string, bool, double, char, long) sextValueTuple = (1, "one", true, 1.1, 'a', 100L); |
ValueTuple <T1,T2,T3,T4,T5,T6,T7> Struct | - Represents a value type 7-tuple | (int, string, bool, double, char, long, decimal) septValueTuple = (1, "one", true, 1.1, 'a', 100L, 1.01m); |
ValueTuple <T1,T2,T3,T4,T5,T6,T7,TRest> Struct | - Represents a value type tuple with 7 elements and an additional generic type for the rest | (int, string, bool, double, char, long, decimal, ValueTuple<int>) octValueTuple = (1, "one", true, 1.1, 'a', 100L, 1.01m, (8)); |
Indexers & Properties
Topic | Description/Answer | C# Code Example |
Indexers | - Allows objects to be indexed in a similar way to arrays. | class SampleIndexer { private int[] arr = new int[100]; public int this[int i] { get { return arr[i]; } set { arr[i] = value; } } } |
Multidimensional Indexers | - Indexers that take multiple parameters. | class Matrix { private int[,] mat = new int[3,3]; public int this[int i, int j] { get { return mat[i, j]; } set { mat[i, j] = value; } } |
Overloading of Indexers | - You can have multiple indexers in a class with different parameters. | class OverloadIndexer { public int[] arrInt = new int[100]; public double[] arrDouble = new double[100]; public int this[int i] { ... } public double this[double d] { ... } } |
Properties | - Allows you to read, write, or compute the value of a private field. | class Person { private string name; public string Name { get { return name; } set { name = value; } } } |
Restrictions on Properties | - No parameters, except indexers. | - Can't be static. |
Inheritance
Topic | Description/Answer | C# Code Example |
Inheritance in C# | - Mechanism to create a new class from an existing class. | class Base {} class Derived : Base {} |
Multilevel Inheritance | - Deriving a class from another derived class. | class Grandparent {} class Parent : Grandparent {} class Child : Parent {} |
Multiple inheritance using interfaces | - Achieving multiple inheritance through interfaces as C# doesn't support it with classes. | interface I1 {} interface I2 {} class Derived : I1, I2 {} |
Inheritance in Constructors | - Base class constructors are called before derived class's. | class Base { public Base() {} } class Derived : Base { public Derived() : base() {} } |
Inheritance in Interfaces | - An interface can inherit from another interface. | interface IBase {} interface IDerived : IBase {} |
Abstract Classes | - Cannot be instantiated. | - Acts as a base class. |
Using sealed class to Prevent Inheritance | - Prevents further derivation. | sealed class NonInheritable {} |
Object Class | - Base class for all .NET classes. | - Provides fundamental methods like ToString(), GetHashCode(), etc. |
Interfaces
Topic | Description/Answer | C# Code Example |
Interface in C# | - Defines a contract that classes or structs can implement. | interface IExample { void MyMethod(); } |
How to use Interface References | - Interface references can point to any object that implements that interface. | IExample exampleObj = new SomeClass(); |
How to Implement Multiple Interfaces Having Same Method Name | - Requires explicit implementation when two interfaces have the same method. | interface IOne { void Show(); } interface ITwo { void Show(); } class Example : IOne, ITwo { void IOne.Show() { } void ITwo.Show() { } } |
Difference between Abstract Class and Interface | - Abstract classes can have implementation and fields. | - Interfaces only declare method signatures. |
Delegates vs Interfaces | - Delegates are reference types that encapsulate a method. | - Interfaces are contracts that classes/structs can implement. |
Explicit Interface Implementation | - Used to implement a member of an interface without exposing it on the implementing class. | interface IExample { void MyMethod(); } class Example : IExample { void IExample.MyMethod() { } } |
Multithreading
Topic | Description/Answer | C# Code Example |
Introduction to Multithreading | - Execution of multiple threads simultaneously. | - Helps in performing multiple operations concurrently in a single process. |
Types of Threads | - Foreground Threads: Continue execution until their task completes. | - Background Threads: Stop executing once the main program stops. |
How to create Threads | - Use the Thread class from System.Threading namespace. | Thread myThread = new Thread(new ThreadStart(MyFunction)); |
Main Thread | - The primary thread on which the main method runs. | Thread mainThread = Thread.CurrentThread; |
Lifecycle and States of a Thread | - Unstarted, Running, WaitSleepJoin, Suspended, Stopped, etc. | ThreadState state = myThread.ThreadState; |
Thread Class | - Represents a thread in C#. | Thread thread = new Thread(new ThreadStart(FunctionName)); |
Scheduling a thread for Execution | - Start a thread using the Start method. | myThread.Start(); |
Check whether a Thread is Alive or not | - Use the IsAlive property. | bool isAlive = myThread.IsAlive; |
Joining Threads | - Makes sure that a thread completes its execution before the main thread continues. | myThread.Join(); |
Terminating a Thread | - Cannot be done directly, but can be done indirectly using interruption or using flags. | myThread.Interrupt(); // or using a flag in thread's method |
Check whether a thread is a background thread or not | - Use the IsBackground property. | bool isBackground = myThread.IsBackground; |
Naming a thread and fetching name of current thread | - Use the Name property of the Thread class. | myThread.Name = "MyThreadName"; string threadName = Thread.CurrentThread.Name; |
Thread Priority in Multithreading | - Determines the execution priority of threads. There are levels like: Lowest, BelowNormal, Normal, AboveNormal, and Highest | myThread.Priority = ThreadPriority.Highest; |
Exception Handling
Topic | Description/Answer | C# Code Example |
Exceptions | - Unpredictable events during program execution | - Can be caught and handled using try-catch blocks. |
System Level Exception vs Application Level Exception | - System Level: Raised by CLR (e.g., NullReferenceException). | - Application Level: Custom exceptions defined by the user. |
public class MyAppException : Exception { } | ||
How to use Multiple Catch Clause | - Handle multiple exceptions separately. | try { ... } catch(ArgumentException ex) { ... } catch(DivideByZeroException ex) { ... } |
Nesting of try and catch blocks | - Placing a try-catch block within another try-catch block. | try { try { ... } catch(Type1 ex) { ... } } catch(Type2 ex) { ... } |
Using finally | - Executed regardless of whether an exception was thrown or not. | try { ... } catch(Exception ex) { ... } finally { ... } |
Collections & Generics
Topic | Description/Answer | C# Code Example |
List | - A dynamic array. | List<int> numbers = new List<int> {1, 2, 3}; |
SortedList with Examples | - Collection of key-value pairs in ascending order. | SortedList<int, string> sortedList = new SortedList<int, string> { {1, "One"}, {2, "Two"} }; |
HashSet | - Collection with no duplicate elements. | HashSet<int> set = new HashSet<int> {1, 2, 3}; |
SortedSet | - Collection with unique elements in sorted order. | SortedSet<int> sortedSet = new SortedSet<int> {3, 1, 2}; |
Dictionary with Examples | - Collection of key-value pairs. | Dictionary<int, string> dict = new Dictionary<int, string> { {1, "One"}, {2, "Two"} }; |
SortedDictionary | - Key-value pairs sorted by keys. | SortedDictionary<int, string> sDict = new SortedDictionary<int, string> { {2, "Two"}, {1, "One"} }; |
Hashtable with Examples | - Non-generic collection of key-value pairs. | Hashtable table = new Hashtable { {1, "One"}, {"Two", 2} }; |
Stack with Examples | - LIFO data structure. | Stack<int> stack = new Stack<int>(); stack.Push(1); |
Queue with Examples | - FIFO data structure. | Queue<int> queue = new Queue<int>(); queue.Enqueue(1); |
LinkedList | - Doubly linked list. | LinkedList<int> linkedList = new LinkedList<int>(); linkedList.AddLast(1); |
Hashtable vs Dictionary | - Hashtable: Non-generic. | - Dictionary: Generic, stronger typing. |
Hashtable ht = new Hashtable(); Dictionary<int, string> dic = new Dictionary<int, string>(); | ||
SortedList vs SortedDictionary | - Both store key-value pairs in sorted order. | - SortedDictionary: faster insertion and removal. |
SortedList<int, string> sl = new SortedList<int, string>(); SortedDictionary<int, string> sd = new SortedDictionary<int, string>(); |
Collections Namespace
Topic | Description/Answer | C# Code Example |
C# | Stack Class | - LIFO (Last In First Out) data structure. |
C# | Queue Class | - FIFO (First In First Out) data structure. |
C# | Array Class | - Fixed-size collection of elements of the same type. |
C# | ArrayList Class | - Dynamic size collection of elements. Can store items of any type. |
C# | Hashtable Class | - Collection of key-value pairs. Supports object keys. |
C# | BitArray Class | - Collection of bits (Booleans). Used for efficient bitwise operations. |
C# | SortedList Class | - Collection of key-value pairs sorted by the keys. |
Generic Namespace
Topic | Description/Answer | C# Code Example |
C# | HashSet<T> Class | - Unordered collection of unique items. |
C# | LinkedList<T> Class | - Doubly-linked list. Allows for item insertion or removal without rearranging the entire structure. |
C# | List<T> Class | - Dynamic size array. Offers methods to add, remove, and find items. |
C# | SortedSet<T> Class | - Collection of unique elements sorted in ascending order. |
Dictionary Class | - Collection of key-value pairs. Can have any type of key and value. | Dictionary<int, string> dictionary = new Dictionary<int, string>() {{1, "One"}, {2, "Two"}}; |
SortedDictionary Class | - Collection of key-value pairs. Maintains order based on the key. Faster retrieval of individual items than Dictionary. | SortedDictionary<int, string> sortedDictionary = new SortedDictionary<int, string>() {{1, "One"}}; |
System Namespace
Topic | Description/Answer | C# Code Example |
BitConverter Class | - Converts base data types to an array of bytes and vice versa. | byte[] bytes = BitConverter.GetBytes(12345); |
Console Class | - Represents the standard input, output, and error streams for console applications. | Console.WriteLine("Hello, World!"); |
Convert Class | - Provides methods to convert various base types to and from other base types. | int i = Convert.ToInt32("123"); |
Decimal Struct | - Represents a 128-bit precise decimal number with 28-29 significant digits. | decimal d = 10.5M; |
Byte Struct | - Represents an 8-bit unsigned integer. | byte b = 255; |
Char Struct | - Represents a character as a UTF-16 code unit. | char c = 'A'; |
Int16 Struct | - Represents a 16-bit signed integer. | Int16 val = 32767; |
Int32 Struct | - Represents a 32-bit signed integer. | Int32 val = 2147483647; |
Int64 Struct | - Represents a 64-bit signed integer. | Int64 val = 9223372036854775807; |
UInt16 Struct | - Represents a 16-bit unsigned integer. | UInt16 val = 65535; |
UInt32 Struct | - Represents a 32-bit unsigned integer. | UInt32 val = 4294967295; |
UInt64 Struct | - Represents a 64-bit unsigned integer. | UInt64 val = 18446744073709551615; |
Specialized Namespace
Topic | Description/Answer | C# Code Example |
C# | ListDictionary Class | - Suitable for collections that have few elements. - Implements IDictionary using singly linked list. |
C# | StringCollection Class | - Represents a collection of strings. - Does not accept null as a valid value. |
C# | OrderedDictionary Class | - Represents a collection of key/value pairs that are ordered by the key in an array. - Supports ordering and indexed access. |
C# | HybridDictionary Class | - Implements IDictionary interface. - Starts off as a ListDictionary and switches to a Hashtable when the count becomes larger than a threshold. |
C# | StringDictionary Class | - Represents a collection of associated String keys and String values. - Key is case-insensitive. |
What’s New in C# 8.0
Topic | Description/Answer | C# Code Example |
C# | ListDictionary Class | - Suitable for collections that have few elements. - Implements IDictionary using singly linked list. |
C# | StringCollection Class | - Represents a collection of strings. - Does not accept null as a valid value. |
C# | OrderedDictionary Class | - Represents a collection of key/value pairs that are ordered by the key in an array. - Supports ordering and indexed access. |
C# | HybridDictionary Class | - Implements IDictionary interface. - Starts off as a ListDictionary and switches to a Hashtable when the count becomes larger than a threshold. |
C# | StringDictionary Class | - Represents a collection of associated String keys and String values. - Key is case-insensitive. |
Windows Forms
Topic | Description/Answer | C# Code Example |
What is Windows Forms(WF) in C#? | - Graphical application interface to create Windows-based apps. - Provides a set of classes for GUI components. | N/A |
Button Control | - Represents a clickable button in a WF application. | Button btn = new Button(); btn.Text = "Click Me"; |
Label Control | - Used to display text on the form. | Label label = new Label(); label.Text = "This is a label."; |
RadioButton Control | - Allows user to choose one option from a set. | RadioButton rbtn1 = new RadioButton(); rbtn1.Text = "Option 1"; |
CheckBox Control | - Allows user to select multiple options. | CheckBox chk1 = new CheckBox(); chk1.Text = "Check Me"; |
TextBox Control | - Provides a user-editable text field. | TextBox txtBox = new TextBox(); |
ComboBox Control | - Drop-down list with items that can be selected. | ComboBox comboBox = new ComboBox(); comboBox.Items.Add("Option 1"); |
ToolTip Class | - Used to display a pop-up message. | ToolTip tooltip = new ToolTip(); tooltip.SetToolTip(button1, "This is a button"); |
RichTextBox Class | - Allows rich formatting (e.g., bold, italic). | RichTextBox rtxtBox = new RichTextBox(); |
MaskedBox Class | - Input field with specific format (e.g., date, phone number). | MaskedTextBox mtxtBox = new MaskedTextBox(); mtxtBox.Mask = "00/00/0000"; |
NumericUpDown Class | - Allows user to select a numeric value. | NumericUpDown numericUpDown = new NumericUpDown(); |
DateTimePicker Class | - Allows user to select a date and/or time. | DateTimePicker dtPicker = new DateTimePicker(); |
ListBox Class | - Displays a list of items to choose from. | ListBox listBox = new ListBox(); listBox.Items.Add("Item 1"); |
GroupBox Class | - Container that can host other controls and group them together. | GroupBox gBox = new GroupBox(); gBox.Text = "Group of Controls"; |
FlowLayoutPanel Class | - A container that arranges its contents in a flow layout. - Controls flow from left-to-right or top-to-bottom based on its properties. | FlowLayoutPanel flowLayout = new FlowLayoutPanel(); |
- Get link
- X
- Other Apps
Comments
Post a Comment