C# Data Types and Variables | int, string, bool, var, dynamic

C# Data Types and Variables | int, string, bool, var, dynamic

🧠 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

💡 Key Takeaways

  • int is for whole numbers
  • string stores textual data
  • bool represents logical values
  • var is statically typed but inferred at compile time
  • dynamic allows 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

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences