C# Flashcards
(49 cards)
How do you read all lines from a text file in C#?
string[] lines = File.ReadAllLines(“filename.txt”);
How do you write all lines to a text file in C#?
File.WriteAllLines(“filename.txt”, lines);
How do you use a foreach loop in C# to print every item in an array?
foreach (var item in array) { Console.WriteLine(item); }
How do you write a while loop that continues until x equals 10?
while (x != 10) { // code here }
How do you ask a user for input from the console in C#?
Console.WriteLine(“Enter your name:”); string name = Console.ReadLine();
How do you convert a string to an integer in C#?
int number = int.Parse(Console.ReadLine());
How do you split a string by spaces in C#?
string[] words = sentence.Split(‘ ‘);
How do you iterate over an array with a for loop in C#?
for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); }
How do you implement bubble sort in C#?
for (int i = 0; i < arr.Length - 1; i++) { for (int j = 0; j < arr.Length - i - 1; j++) { if (arr[j] > arr[j + 1]) { var temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; }}}
How do you implement merge sort in C# (overview)?
Split the array into halves, recursively sort each half, and merge them. See next card for code.
What is a simple example of merge sort in C#?
void MergeSort(int[] array) { if (array.Length <= 1) return; int mid = array.Length / 2; int[] left = array[..mid]; int[] right = array[mid..]; MergeSort(left); MergeSort(right); Merge(array, left, right); }
How do you define a class in C#?
public class Person { public string Name; public int Age; }
How do you create an object from a class in C#?
Person p = new Person(); p.Name = “Alice”; p.Age = 30;
What is a constructor in C#?
A constructor is a method that runs when an object is created: public Person(string name) { Name = name; }
How do you use inheritance in C#?
class Student : Person { public string School; }
What is polymorphism in C#?
Polymorphism allows methods to behave differently depending on the object. Use virtual and override keywords.
How do you declare a method in C#?
public int Add(int a, int b) { return a + b; }
What is the difference between == and .Equals() in C#?
== compares value or reference depending on the type; .Equals() is a method you can override for custom comparison.
How do you check if a string contains another string in C#?
if (text.Contains(“keyword”)) { /* code */ }
How do you convert a number to a string in C#?
string s = number.ToString();
How do you parse a string into a double safely in C#?
double.TryParse(input, out double result);
How do you define and use an array in C#?
int[] numbers = {1, 2, 3}; Console.WriteLine(numbers[0]);
How do you define a list and add to it in C#?
List<int> nums = new List<int>(); nums.Add(5);</int></int>
How do you use a switch statement in C#?
switch (value) { case 1: Console.WriteLine(“One”); break; default: Console.WriteLine(“Other”); break; }