C# & ASP.NET Topic
C# Introduction - Syntax & Data Types
C# (pronounced "C Sharp") is a modern, object-oriented programming language developed by Microsoft. It's:
-
Statically typed - Types are checked at compile time
-
Type-safe - Prevents many common programming errors
-
Object-oriented - Based on classes and objects
-
Cross-platform - Runs on Windows, Linux, macOS via .NET
Basic Syntax Structure
csharp
using System; // Namespace declaration
namespace HelloWorld // Namespace definition
{
class Program // Class definition
{
static void Main(string[] args) // Main method - entry point
{
Console.WriteLine("Hello, World!"); // Statement
}
}
}
Variables and Data Types
Variable Declaration
csharp
// Explicit typing
int age = 25;
string name = "John";
double salary = 50000.50;
bool isEmployed = true;
// Multiple declarations
int x = 5, y = 10, z = 15;
The var Keyword
csharp
// var - compiler infers the type
var age = 25; // int
var name = "John"; // string
var salary = 50000.50; // double
var isEmployed = true; // bool
// var must be initialized
var valid = "Hello"; // OK
// var invalid; // ERROR - must be initialized
// Useful for complex types
var names = new List<string>(); // List<string>
Basic Data Types
1. Numeric Types
Integer Types
csharp
byte smallNumber = 255; // 0 to 255 (1 byte)
sbyte signedByte = -128; // -128 to 127 (1 byte)
short shortNumber = 32000; // -32,768 to 32,767 (2 bytes)
ushort unsignedShort = 65000; // 0 to 65,535 (2 bytes)
int number = 2147483647; // -2.1B to 2.1B (4 bytes)
uint unsignedInt = 4294967295; // 0 to 4.3B (4 bytes)
long bigNumber = 9223372036854775807; // Very large (8 bytes)
ulong unsignedLong = 18446744073709551615; // Very large unsigned (8 bytes)
Floating-Point Types
csharp
float price = 19.99f; // 7-digit precision, suffix 'f' required
double distance = 123.456; // 15-digit precision (default for decimals)
decimal money = 123.456m; // 28-digit precision, suffix 'm' required (financial)
2. Boolean Type
csharp
bool isActive = true;
bool isComplete = false;
bool canProceed = 10 > 5; // Expression results in boolean
// Common usage
if (isActive)
{
Console.WriteLine("System is active");
}
3. Character Type
csharp
char grade = 'A'; // Single character
char symbol = '$';
char newLine = '\n'; // Escape sequence
char unicodeChar = '\u0041'; // Unicode character 'A'
Strings
String Basics
csharp
string firstName = "John";
string lastName = "Doe";
string emptyString = "";
string nullString = null;
// String concatenation
string fullName = firstName + " " + lastName;
string greeting = "Hello " + fullName;
// String interpolation (C# 6.0+)
string message = $"Welcome {firstName} {lastName}";
string calculation = $"The result is {5 + 3}";
// Verbatim strings (ignore escape sequences)
string path = @"C:\Users\John\Documents";
string multiLine = @"This is a
multi-line
string";
Common String Operations
csharp
string text = "Hello World";
// Properties
int length = text.Length; // 11
bool isEmpty = string.IsNullOrEmpty(text); // false
// Methods
string upper = text.ToUpper(); // "HELLO WORLD"
string lower = text.ToLower(); // "hello world"
bool contains = text.Contains("Hello"); // true
string substring = text.Substring(6); // "World"
string replaced = text.Replace("World", "C#"); // "Hello C#"
// Comparison
bool equal = text.Equals("hello world", StringComparison.OrdinalIgnoreCase);
int position = text.IndexOf("World"); // 6
// Splitting and joining
string[] words = text.Split(' ');
string joined = string.Join("-", words); // "Hello-World"
Type Casting and Conversions
1. Implicit Casting
csharp
// Automatic when no data loss (smaller to larger types)
int smallNumber = 100;
long bigNumber = smallNumber; // Implicit cast: int → long
float floatValue = 3.14f;
double doubleValue = floatValue; // float → double
char character = 'A';
int asciiValue = character; // char → int
2. Explicit Casting
csharp
// Manual casting when potential data loss
double price = 19.99;
int intPrice = (int)price; // 19 - truncates decimal
long bigValue = 123456789;
int smallValue = (int)bigValue; // Possible overflow
// Checked context for overflow detection
checked
{
// This would throw OverflowException if overflow occurs
// int result = (int)bigValue;
}
3. Conversion Methods
Parse Methods
csharp
string numberText = "123";
int number = int.Parse(numberText); // 123
double value = double.Parse("45.67"); // 45.67
bool flag = bool.Parse("true"); // true
// Parse with exception handling
try
{
int result = int.Parse("abc"); // Throws FormatException
}
catch (FormatException ex)
{
Console.WriteLine("Invalid number format");
}
TryParse Methods (Safe Conversion)
csharp
string input = "123";
int result;
if (int.TryParse(input, out result))
{
Console.WriteLine($"Successfully parsed: {result}");
}
else
{
Console.WriteLine("Failed to parse input");
}
// Modern C# (C# 7.0+) with inline variable declaration
if (int.TryParse(input, out int parsedValue))
{
Console.WriteLine($"Parsed value: {parsedValue}");
}
Convert Class
csharp
// More flexible conversion methods
string text = "100";
int number = Convert.ToInt32(text); // 100
double value = Convert.ToDouble("99.99"); // 99.99
bool boolean = Convert.ToBoolean("true"); // true
// Handles null values
string nullString = null;
int defaultNumber = Convert.ToInt32(nullString); // 0
4. Boxing and Unboxing
csharp
// Boxing - value type to object reference
int number = 42;
object boxed = number; // Boxing
// Unboxing - object reference back to value type
int unboxed = (int)boxed; // Unboxing
// Note: Unboxing must be to exact type
// This would throw InvalidCastException:
// double wrong = (double)boxed;
Practical Examples
Calculator with Type Safety
csharp
using System;
class Calculator
{
static void Main()
{
Console.Write("Enter first number: ");
string input1 = Console.ReadLine();
Console.Write("Enter second number: ");
string input2 = Console.ReadLine();
// Safe conversion with TryParse
if (double.TryParse(input1, out double num1) &&
double.TryParse(input2, out double num2))
{
double sum = num1 + num2;
double product = num1 * num2;
Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Product: {product}");
Console.WriteLine($"Average: {(num1 + num2) / 2}");
}
else
{
Console.WriteLine("Invalid input! Please enter valid numbers.");
}
}
}
String Manipulation Demo
csharp
using System;
class StringDemo
{
static void Main()
{
string sentence = "The quick brown fox jumps over the lazy dog";
// Various string operations
Console.WriteLine($"Original: {sentence}");
Console.WriteLine($"Length: {sentence.Length}");
Console.WriteLine($"Uppercase: {sentence.ToUpper()}");
Console.WriteLine($"Contains 'fox': {sentence.Contains("fox")}");
Console.WriteLine($"Index of 'jumps': {sentence.IndexOf("jumps")}");
// Word count
string[] words = sentence.Split(' ');
Console.WriteLine($"Word count: {words.Length}");
// Reverse words
Array.Reverse(words);
string reversed = string.Join(" ", words);
Console.WriteLine($"Reversed: {reversed}");
}
}
Type Conversion Utility
csharp
using System;
class ConversionDemo
{
static void Main()
{
DemonstrateConversions();
DemonstrateStringsAndNumbers();
}
static void DemonstrateConversions()
{
// Implicit conversions
int intValue = 100;
long longValue = intValue; // Implicit
Console.WriteLine($"int to long: {longValue}");
// Explicit conversions
double doubleValue = 99.99;
int truncated = (int)doubleValue; // Explicit
Console.WriteLine($"double to int: {truncated}");
// Conversion methods
string numberText = "123.45";
if (decimal.TryParse(numberText, out decimal decimalValue))
{
Console.WriteLine($"String to decimal: {decimalValue}");
}
}
static void DemonstrateStringsAndNumbers()
{
// Number formatting
int quantity = 42;
double price = 19.99;
string message = $"{quantity} items at ${price} each = ${quantity * price}";
Console.WriteLine(message);
// Boolean expressions
bool inStock = true;
bool canAfford = price * quantity < 1000;
Console.WriteLine($"In stock: {inStock}");
Console.WriteLine($"Can afford: {canAfford}");
Console.WriteLine($"Should buy: {inStock && canAfford}");
}
}
Key Points to Remember
-
Use
varwhen the type is obvious from the right-hand side -
Prefer
TryParse()overParse()for user input -
Use
decimalfor financial calculations - avoids floating-point errors -
Strings are immutable - operations return new strings
-
Be careful with explicit casting - can cause data loss or exceptions
-
Use
string.IsNullOrEmpty()to check for null or empty strings -
Choose the right numeric type based on range and precision needs
This foundation in C# syntax, variables, data types, and conversions will prepare you for more advanced programming concepts in C#!
Comments (1)
Great tutorial