Basic Syntax and Data Types in C#: Variables, Constants, Operators & Type Conversion

1. Basic Syntax and Data Types

Q: What is the basic syntax of a C# program?

C# programs use a structured, object-oriented syntax with namespaces, classes, and a Main method as the entry point. Key elements include:

Q: What are the basic data types in C#?

C# provides value types and reference types:

Value Types: Store data directly, allocated on the stack.

Reference Types: Store references to data, allocated on the heap.

Q: How do C# data types differ from C/C++?

2. Variables, Constants, and Data Types

Q: What are variables in C#?

Variables are named storage locations for data, associated with a specific data type. They must be declared before use.

Syntax:

type variableName = value; // e.g., int age = 25;

Q: What are constants in C#?

Constants are immutable values set at compile-time, declared with the const keyword. They cannot change during execution.

Syntax:

const type constantName = value; // e.g., const double PI = 3.14159;

Q: What is the var keyword in C#?

The var keyword enables implicit typing, where the compiler infers the type from the assigned value. It’s used for local variables and requires initialization.

Example:

var number = 42; // Inferred as int
var name = "Krishna"; // Inferred as string

Q: Can you give an example of variables and constants in C#?

using System;

namespace VariablesAndConstants
{
    class Program
    {
        const double PI = 3.14159; // Constant
        static void Main(string[] args)
        {
            int age = 25; // Variable
            var name = "Krishna"; // Implicitly typed variable
            double radius = 5.0;
            
            Console.WriteLine($"Name: {name}, Age: {age}");
            Console.WriteLine($"Area of circle: {PI * radius * radius}");
            // PI = 3.14; // Error: Cannot modify constant
        }
    }
}

Output:

Name: Krishna, Age: 25
Area of circle: 78.53975

Q: What are nullable value types in C#?

Nullable value types (C# 2.0+) allow value types to have a null value, declared with ?. Useful for scenarios where a value might be undefined.

Example:

int? nullableInt = null; // Nullable int
if (nullableInt.HasValue) {
    Console.WriteLine(nullableInt.Value);
} else {
    Console.WriteLine("Value is null");
}

3. Operators and Expressions

Q: What are operators in C#?

Operators are symbols that perform operations on operands (variables, literals). C# operators include:

Q: What are expressions in C#?

Expressions are combinations of operands and operators that evaluate to a value.

Example:

int x = 5 + 3 * 2; // Expression: 5 + (3 * 2) = 11

Q: Can you give an example of operators and expressions in C#?

using System;

namespace OperatorsAndExpressions
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10, b = 3;
            // Arithmetic
            Console.WriteLine($"Sum: {a + b}"); // 13
            Console.WriteLine($"Modulus: {a % b}"); // 1
            
            // Relational
            Console.WriteLine($"a > b: {a > b}"); // true
            
            // Logical
            bool x = true, y = false;
            Console.WriteLine($"x && y: {x && y}"); // false
            
            // Ternary and null-coalescing
            string name = null;
            string result = name ?? "Unknown";
            Console.WriteLine($"Name: {result}"); // Unknown
            
            // Null-conditional
            string[] arr = null;
            Console.WriteLine($"Array length: {arr?.Length ?? 0}"); // 0
        }
    }
}

Output:

Sum: 13
Modulus: 1
a > b: true
x && y: false
Name: Unknown
Array length: 0

Q: How do operators in C# differ from C/C++?

4. Type Conversion and Casting

Q: What is type conversion in C#?

Type conversion is the process of converting a value from one data type to another. C# supports:

Q: How do you perform implicit and explicit casting in C#?

Implicit: Done automatically when no data loss occurs.

int i = 42;
double d = i; // Implicit: int to double

Explicit: Use (type) or conversion methods for potentially lossy conversions.

double d = 42.99;
int i = (int)d; // Explicit: truncates to 42

Q: What are conversion methods in C#?

Methods like Convert.ToInt32, Int32.Parse, or ToString handle conversions safely, often with error handling.

Example:

string s = "123";
int num = Convert.ToInt32(s); // Converts string to int

Q: Can you give an example of type conversion and casting in C#?

using System;

namespace TypeConversion
{
    class Program
    {
        static void Main(string[] args)
        {
            // Implicit conversion
            int i = 42;
            double d = i; // int to double
            Console.WriteLine($"Implicit: int {i} to double {d}"); // 42.0
            
            // Explicit casting
            double d2 = 99.99;
            int i2 = (int)d2; // Truncates to 99
            Console.WriteLine($"Explicit: double {d2} to int {i2}");
            
            // Conversion methods
            string s = "123";
            try {
                int num = int.Parse(s);
                Console.WriteLine($"Parsed string to int: {num}");
            } catch (FormatException) {
                Console.WriteLine("Invalid number format");
            }
            
            // ToString
            int x = 456;
            string str = x.ToString();
            Console.WriteLine($"Int to string: {str}");
        }
    }
}

Output:

Implicit: int 42 to double 42
Explicit: double 99.99 to int 99
Parsed string to int: 123
Int to string: 456

Q: What are common mistakes with type conversion in C#?

Q: What are best practices for variables, constants, operators, and type conversion in C#?

Variables and Constants:

Operators:

Type Conversion:

General: