🧠 Data Types and Variables in C#
In C#, variables are used to store data, and every variable has a type. Understanding data types is essential for writing reliable, type-safe code.
📘 Basic Data Types in C#
- int - stores integers like 1, -45, 1000
- string - stores sequences of characters
- bool - stores true or false values
- var - implicitly typed variable
- dynamic - resolves type at runtime
📝 Example: Declaring Variables in C#
using System;
class Program {
static void Main() {
int age = 25;
string name = "Alice";
bool isStudent = true;
var score = 89.5; // inferred as double
dynamic anything = "Hello";
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Age: {age}");
Console.WriteLine($"Is Student: {isStudent}");
Console.WriteLine($"Score: {score}");
Console.WriteLine($"Dynamic Value: {anything}");
anything = 2024; // dynamic allows reassignment to different type
Console.WriteLine($"Dynamic Changed: {anything}");
}
}
📤 Sample Output
Name: Alice
Age: 25
Is Student: True
Score: 89.5
Dynamic Value: Hello
Dynamic Changed: 2024
Age: 25
Is Student: True
Score: 89.5
Dynamic Value: Hello
Dynamic Changed: 2024
💡 Key Takeaways
intis for whole numbersstringstores textual databoolrepresents logical valuesvaris statically typed but inferred at compile timedynamicallows type changes at runtime
📌 Conclusion
C# provides strong typing with flexibility using var and dynamic. Knowing the right data type to use is crucial for performance and clarity. Try declaring your own variables and observe how types behave!

Post a Comment