C# Programming

#csharp#dotnet

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