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:
- Namespaces: Organize code to avoid name conflicts (e.g.,
using System;). - Classes/Structs: Define objects or data structures.
- Main Method: The program’s entry point (
static void Main(string[] args)). - Statements: End with semicolons (
;). - Case Sensitivity: C# is case-sensitive (e.g.,
Main≠main).
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.
- Integers:
byte(0-255),sbyte(-128 to 127),short,ushort,int,uint,long,ulong. - Floating-Point:
float(single-precision),double(double-precision),decimal(high-precision). - Boolean:
bool(trueorfalse). - Character:
char(single Unicode character, e.g.,'A'). - Structs: User-defined (e.g.,
struct Point { public int X, Y; }). - Enum: User-defined enumeration (e.g.,
enum Day { Monday, Tuesday }).
Reference Types: Store references to data, allocated on the heap.
- String: Immutable text (e.g.,
"Hello"). - Object: Base type for all types (
object). - Class: User-defined (e.g.,
class Person {}). - Array: Collections (e.g.,
int[]). - Interface/Delegate: For polymorphism and events.
Q: How do C# data types differ from C/C++?
- C#: Managed, type-safe, with garbage collection. Includes
string,decimal, and nullable types (e.g.,int?). All types derive fromobject. - C/C++: Unmanaged, manual memory management. Lacks built-in
stringordecimal, useschar*orstd::string. No nullable types. - C# Advantage: Safer, higher-level abstractions, automatic memory management.
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:
- Arithmetic:
+,-,*,/,%(modulus). - Relational:
==,!=,<,>,<=,>=. - Logical:
&&(and),||(or),!(not). - Bitwise:
&,|,^(XOR),~,<<,>>. - Assignment:
=,+=,-=,*=,/=, etc. - Ternary:
condition ? valueIfTrue : valueIfFalse. - Null-Coalescing:
??(returns left operand if not null, else right). - Null-Conditional:
?.(accesses members only if not null).
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++?
- C#: Includes modern operators like
??,?., and=>(for lambdas). Type-safe, no pointer arithmetic. - C/C++: Supports pointer arithmetic (
*,->) and unsafe operations. Lacks??or?.. - C# Advantage: Safer and more expressive operators for modern programming.
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:
- Implicit Conversion: Automatic, safe conversions (e.g.,
inttodouble). - Explicit Conversion (Casting): Manual conversion, potentially lossy (e.g.,
doubletoint). - Conversion Methods: Using methods like
Convert.ToInt32,ToString, orParse.
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#?
- Attempting invalid conversions (e.g.,
stringtointwithout parsing). - Ignoring potential data loss in explicit casts (e.g.,
doubletoint). - Not handling exceptions in
ParseorConvertmethods (e.g.,FormatException). - Misusing
varleading to unclear type inference.
Q: What are best practices for variables, constants, operators, and type conversion in C#?
Variables and Constants:
- Use meaningful names (e.g.,
ageinstead ofx). - Prefer
constfor immutable values known at compile-time. - Use
varonly when the type is obvious from the initializer.
Operators:
- Use
??and?.for null safety. - Avoid complex expressions; break them into smaller, readable parts.
Type Conversion:
- Prefer implicit conversions when safe.
- Use
try-catchwithParseorConvertfor robust string conversions. - Use
TryParseto avoid exceptions (e.g.,int.TryParse). - Document explicit casts to clarify intent.
General:
- Initialize variables to avoid null or uninitialized errors.
- Use nullable types (
T?) for optional values. - Enable nullable reference types (
<Nullable>enable</Nullable>) in modern C#.