Quick notes on C# with examples
2025-04-24
C# Programming ๐
String Formatting ๐งต
string text = "Hello, {0}! Today is {1:D}.";
Console.WriteLine(string.Format(text, "Alice", DateTime.Now));
// Output: Hello, Alice! Today is Wednesday, April 24, 2025.
string template = "Product: {0}, Price: {1:C}";
Console.WriteLine(string.Format(template, "Laptop", 999.99));
// Output: Product: Laptop, Price: $999.99
string template = "|{0,-10}|{1,10:N2}|";
string result = string.Format(template, "Item", 1234.567);
Console.WriteLine(result);
// Output: |Item | 1,234.57|
Abstract Class & Methods ๐ ๏ธ
What is it? ๐ค
- Abstract Class: A blueprint class that can't be instantiated directly.
- Abstract Method: A method without a body that must be implemented in derived classes.
Key Points ๐
- Abstract classes can have both abstract and non-abstract methods.
- Abstract methods must be overridden in derived classes.
- Virtual methods can be overridden but aren't mandatory.
Example Code ๐ป
abstract class Animal {
public abstract void Speak(); // Abstract method ๐พ
public void Sleep() {
Console.WriteLine("Sleeping... ๐ด");
}
}
class Dog : Animal {
public override void Speak() {
Console.WriteLine("Woof! ๐ถ");
}
}
class Cat : Animal {
public override void Speak() {
Console.WriteLine("Meow! ๐ฑ");
}
}
Animal myDog = new Dog();
myDog.Speak(); // Output: Woof! ๐ถ
myDog.Sleep(); // Output: Sleeping... ๐ด
Meme Time ๐
Abstract Class: "I'm the blueprint, not the builder!"
Derived Class: "Got it, boss! I'll do the heavy lifting. ๐ช"
GetValueOrDefault() ๐
int? nullableInt = null;
int value1 = nullableInt.GetValueOrDefault(); // returns 0, the default for int
nullableInt = 5;
int value2 = nullableInt.GetValueOrDefault(); // returns 5, the actual value
int value3 = nullableInt.GetValueOrDefault(10); // returns 5, because nullableInt has a value
nullableInt = null;
int value4 = nullableInt.GetValueOrDefault(10); // returns 10, the specified default value