Basics Of C
Basics Of C
Visual Studio 2022 is a modern, 64-bit IDE designed for efficient and powerful
development of applications across platforms.
Key Highlights
• 64-bit Support: Handles larger projects and solutions without performance issues.
• Hot Reload: Modify .NET or C++ apps while debugging without restarting.
• Git Integration: Built-in tools for branching, committing, and collaboration.
• AI-Assisted Development: IntelliCode provides smart code suggestions.
• Cross-Platform Development: Build apps for Windows, macOS, Android, iOS, and
Linux.
Essential Shortcuts
Action Shortcut
Open Solution Explorer Ctrl + Alt + L
Build Solution Ctrl + Shift + B
Start Debugging F5
Stop Debugging Shift + F5
Step Into (Debugging) F11
Step Over (Debugging) F10
Find and Replace Ctrl + F / Ctrl + H
Go to Definition F12
Quick Actions (Refactor) Ctrl + .
Open Terminal Ctrl + (backtick)
Toggle Comment Ctrl + K, Ctrl + C
Uncomment Code Ctrl + K, Ctrl + U
Format Document Ctrl + K, Ctrl + D
Navigate to File/Type/Symbol Ctrl + T
Show IntelliSense Suggestions Ctrl + Space
Close Active Tab Ctrl + F4
Important Features
• IntelliSense: Smart code completion and hints for faster development.
• Live Share: Real-time collaboration with teammates for editing and debugging.
• Performance Profiler: Analyze and optimize application performance.
• Azure Integration: Seamless deployment to Azure cloud.
Customization Tips
• Change Theme: Tools > Options > Environment > General > Color
Theme.
• Extensions: Install tools like ReSharper or Prettier from the Extensions
Marketplace.
• Keyboard Mapping: Customize shortcuts via Tools > Options > Keyboard.
Supported Workloads
• Desktop Development: .NET, C++, Python.
• Web Development: ASP.NET, JavaScript, Node.js.
• Mobile Development: Xamarin, .NET MAUI.
• Game Development: Unity, Unreal Engine.
Getting Started
• Download: Visual Studio 2022
• System Requirements:
– OS: Windows 10/11
– RAM: 4 GB (8 GB or more recommended)
– Disk Space: 20-50 GB depending on workloads.
Capitalization Summary
Identifier Rules for Naming Notes/Examples
Class Pascal Case MyClass
Attribute Class Pascal Case Suffix with Attribute.
Exception Class Pascal Case Suffix with Exception.
Constant Pascal Case MaxValue.
Enum Type Pascal Case Prefix with Enm, e.g., EnmStatus.
Enum Values Pascal Case Active.
Event Pascal Case DataChanged.
Interface Pascal Case Prefix with I, e.g., ICustomer.
Local Variable Camel Case userName.
Method Pascal Case GetData().
Namespace Pascal Case MyApp.Core.
Identifier Rules for Naming Notes/Examples
Property Pascal Case FirstName.
Public Instance Field Pascal Case Rarely used (use properties instead).
Protected Instance Field Camel Case Rarely used (use properties instead).
Parameter Camel Case filePath.
• Examples:
Interface
• Naming: Pascal Case, prefix with I.
• Example:
interface ICustomer { }
Generic Types
• Use a single capital letter, e.g., T, K.
• Example:
Method
• Naming: Pascal Case, use verbs or verb-object pairs.
• Examples:
Property
• Naming: Pascal Case, avoid prefixes like Get or Set.
• Example:
• Examples:
Variable
• Naming: Camel Case, avoid single characters or enumerating names like var1,
var2.
• Example:
string userName;
Enum
• Pascal Case for type and values. Use [Flags] for bit-masks.
• Example:
[Flags]
public enum CustomerTypes { Consumer, Commercial }
General Guidelines
1. Use Camel Case or Pascal Case consistently.
2. Avoid numeric characters and abbreviations.
3. Prefix boolean variables with is, can, or has.
4. Do not include parent class names in property names.
Exception Handling
• Avoid try/catch for flow control.
• Examples:
• Example:
/// <summary>
/// Executes the given command.
/// </summary>
/// <param name="commandText">The command to execute.</param>
public void Execute(string commandText) { }
Flow Control
• Structure classes with regions:
1. Private Members
2. Public Properties
3. Constructors
4. Public Methods
5. Private Methods
• Example:
Introduction to C
What is C#?
• C# (pronounced “C-Sharp”) is a modern, object-oriented, and type-safe
programming language developed by Microsoft.
• It is part of the .NET framework ecosystem and is widely used for building:
– Desktop applications
– Web applications
– Mobile apps
– Game development (via Unity)
– Cloud-based services and APIs
Features of C
1. Object-Oriented: Supports concepts like inheritance, polymorphism, and
encapsulation.
2. Type-Safe: Prevents unintended type conversions, ensuring code reliability.
3. Rich Libraries: Access to a vast set of libraries in the .NET framework for various
functionalities.
4. Cross-Platform: Develop applications that run on Windows, macOS, and Linux
using .NET Core/6+.
5. Automatic Memory Management: Managed by the .NET runtime using garbage
collection.
6. Strong Community Support: Regular updates, extensive documentation, and
community resources.
Steps to Run:
1. Open Visual Studio and create a new project:
– Go to File > New > Project.
– Select Console App (.NET).
2. Name your project (e.g., HelloWorld) and click Create.
3. Replace the default code in Program.cs with the above example.
4. Press Ctrl + F5 or click Start Without Debugging to run the program.
5. The output Hello, World! will appear in the console.
Basic Structure
using System; // Namespace declaration
Key Components
1. Namespace
• Organizes classes and avoids naming conflicts.
• Example:
namespace MyApp
{
class Example { }
}
2. Class
• A blueprint for creating objects and encapsulating methods and variables.
• Example:
class Person
{
public string Name { get; set; }
}
3. Main Method
• The starting point of the program.
• Can take optional parameters like string[] args for command-line arguments.
• Example:
static void Main(string[] args)
{
Console.WriteLine("Program Starts Here");
}
4. Statements
• The logical instructions that the program executes.
• Example:
Console.WriteLine("This is a statement.");
Common Errors
1. Missing Semicolon:
– Error: ; expected.
– Fix: Ensure every statement ends with a ;.
2. Case Sensitivity:
– Error: Console or Main spelled incorrectly.
– Fix: Ensure correct capitalization.
3. Missing Main Method:
– Error: Program has no entry point.
– Fix: Define a Main method as the entry point.
• Example:
// File: Program.cs
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
2. Projects
• A project represents a single application, library, or service.
• Contains all code files, dependencies, and settings required to build and run the
application.
• Types:
– Console App: Command-line applications.
– Windows App: Desktop GUI applications.
– Class Library: Reusable code libraries.
3. Solutions
• A solution is a container for one or more projects.
• Used to manage large applications with multiple components (e.g., frontend,
backend).
• Solution files have the extension .sln.
Reference Types
• Store references to memory locations.
• Examples:
– string: Sequence of characters.
– object: Base type of all types in C#.
– class: User-defined reference type.
Nullable Types
• Allow value types to represent null.
• Example:
Variables in C
• Definition: A variable is a named memory location used to store data.
• Declaration:
Variable Types
1. Local Variables:
– Declared inside a method or block.
– Example:
void Example()
{
int count = 5; // Local variable
}
2. Instance Variables:
– Declared in a class but outside methods.
– Example:
class Example
{
private string name; // Instance variable
}
3. Static Variables:
– Shared across all instances of a class.
– Example:
Type Conversion in C
1. Implicit Conversion:
– Example:
– Example:
double value = 10.5;
int result = (int)value; // Explicit conversion
– Example:
4. Parsing:
– Example:
5. TryParse Method:
– Example:
2. Relational Operators
• Compare values and return a boolean result.
• Examples:
– == (Equal): a == b
– != (Not Equal): a != b
– > (Greater Than): a > b
– < (Less Than): a < b
3. Logical Operators
• Combine conditional expressions.
• Examples:
– && (AND): a > b && c > d
– || (OR): a > b || c > d
– ! (NOT): !isTrue
4. Assignment Operators
• Assign values to variables.
• Examples:
– =: a = 10;
– +=: a += 5; (Equivalent to a = a + 5).
6. Bitwise Operators
• Operate at the bit level.
• Examples:
– & (AND): a & b
– | (OR): a | b
– ^ (XOR): a ^ b
Expressions
• Definition: A combination of variables, operators, and values that produce a result.
• Examples:
– Arithmetic Expression:
int result = (a + b) * c;
– Logical Expression:
Operator Precedence
• Defines the order of operations in an expression.
• Example:
– Multiplication (*) and Division (/) are evaluated before Addition (+) and
Subtraction (-).
– Use parentheses () to override precedence.
Statements
What Are Statements?
• Statements are individual instructions executed by the C# compiler.
• They can perform actions like variable declarations, assignments, method calls, or
loops.
• Each statement ends with a semicolon (;).
Types of Statements
1. Declaration Statements:
– Example:
2. Expression Statements:
– Example:
– Examples:
5. Block Statements:
– Example:
if (number > 0)
{
Console.WriteLine("Positive number");
Console.WriteLine("End of check");
}
Understanding Arrays
What Are Arrays?
• Arrays are a collection of elements of the same type, stored in contiguous memory
locations.
• They allow multiple values to be stored in a single variable.
Examples
1. Declaration and Initialization:
2. Inline Initialization:
Types of Arrays
1. Single-Dimensional Array:
– Example:
int[] numbers = { 1, 2, 3, 4, 5 };
2. Multi-Dimensional Array:
– Example:
3. Jagged Array:
– Example:
Array Methods
1. Length:
– Example:
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers.Length); // Outputs: 3
2. Sort:
– Example:
int[] numbers = { 3, 1, 2 };
Array.Sort(numbers);
3. Reverse:
– Example:
Array.Reverse(numbers);
Defining a Method
Syntax
accessModifier returnType MethodName(parameters)
{
// Method body
}
Example
public int Add(int a, int b)
{
return a + b; // Returns the sum of two numbers
}
Calling a Method
Syntax
MethodName(arguments);
Example
class Program
{
static void Main(string[] args)
{
Program obj = new Program();
int result = obj.Add(10, 20); // Call the Add method
Console.WriteLine(result); // Outputs: 30
}
Types of Methods
1. Parameterless Methods
• Do not take any input arguments.
• Example:
2. Parameterized Methods
• Accept input arguments.
• Example:
3. Static Methods
• Called without creating an object of the class.
• Example:
• Example:
Returning Values
Syntax
return value;
Example:
public int Multiply(int a, int b)
{
return a * b;
}
• Example:
Recursion
• A method calling itself to solve a problem.
• Example:
1. Encapsulation
Definition:
• Encapsulation is the bundling of data (fields) and methods (functions) into a single
unit (class) while restricting direct access to the internal state.
Key Features:
1. Access Modifiers:
– Types:
class Employee
{
private int _id; // Private field
2. Properties:
– Provide controlled access to private fields.
– Example:
3. Benefits:
2. Abstraction
Definition:
• Abstraction is the process of hiding the implementation details while exposing only
the essential features of an object.
Implementation in C#:
1. Abstract Classes:
– Cannot be instantiated.
– Example:
2. Interfaces:
– Example:
interface IAnimal
{
void Speak(); // Abstract method
}
3. Benefits:
– Simplifies code by focusing on what an object does rather than how it does it.
– Promotes flexibility and scalability.
3. Inheritance
Definition:
• Inheritance is a mechanism where one class (child/derived) inherits the properties
and methods of another class (parent/base).
Implementation in C#:
1. Syntax:
class BaseClass
{
public void Display()
{
Console.WriteLine("Base Class Method");
}
}
2. Types of Inheritance:
– Example:
class BaseClass
{
public void Greet() => Console.WriteLine("Hello from
Base Class");
}
4. Benefits:
Types of Polymorphism:
1. Compile-Time (Static) Polymorphism:
– Example:
class Calculator
{
public int Add(int a, int b) => a + b;
public double Add(double a, double b) => a + b;
}
– Example:
class Animal
{
public virtual void Speak() =>
Console.WriteLine("Animal speaks");
}
Benefits:
• Enhances flexibility and code readability.
• Supports dynamic behavior.
– Parameterized Constructor:
– Copy Constructor:
Destructors
• Used to clean up resources when an object is destroyed.
• Example:
~MyClass()
{
Console.WriteLine("Destructor called");
}
Static Members
• Belong to the class rather than any object.
• Example:
class Counter
{
public static int Count = 0;
}
• Example:
Types of Scopes
1. Local Scope:
– Example:
void MyMethod()
{
int x = 10; // Local variable
Console.WriteLine(x); // Accessible within MyMethod
}
2. Method Scope:
– Variables are declared inside a method and can only be accessed within that
method.
– Example:
void Display()
{
string message = "Hello";
Console.WriteLine(message); // Accessible within
Display method
}
3. Class Scope:
– Example:
class MyClass
{
int count = 5; // Class scope
4. Global Scope:
– Variables or methods declared at the class level and can be accessed from
anywhere in the class or program (if public).
Accessibility Modifiers in C
• Accessibility Modifiers control the visibility of types and their members. They
define where a class, field, method, or property can be accessed.
– The member is accessible from anywhere, both inside and outside the class.
– Example:
2. private:
– Example:
3. protected:
– The member is accessible within the class and by derived (child) classes.
– Example:
4. internal:
– The member is accessible within the same assembly (project) but not outside
it.
– Example:
internal void Display()
{
Console.WriteLine("Inside the assembly");
}
5. protected internal:
– The member is accessible from within the same assembly and by derived
classes.
– Example:
6. private protected:
– The member is accessible only within the same class or derived classes
within the same assembly.
– Example:
Using Namespaces:
• To access a class or method from a different namespace, you can either use a fully
qualified name or the using directive.
Example:
using MyApplication;
class Program
{
static void Main()
{
MyClass obj = new MyClass(); // Access MyClass from
MyApplication namespace
}
}
System Namespace:
• The System namespace is a predefined namespace that contains basic classes used
by many programs, such as Console, String, Int32, etc.
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!"); // Access
System.Console
}
}
– Example:
using System;
2. System.Collections Namespace:
– Example:
using System.Collections.Generic;
3. System.IO Namespace:
– Contains classes for reading from and writing to files and data streams.
– Example:
using System.IO;
4. System.Linq Namespace:
– Example:
using System.Linq;
5. System.Threading Namespace:
– Example:
using System.Threading;
Creating an Assembly in C
• When you compile a C# program, the output file (either .exe or .dll) is the
assembly.
// File: MyLibrary.cs
public class MyLibraryClass
{
public void PrintMessage()
{
Console.WriteLine("Hello from MyLibrary!");
}
}
2. Using Command Line: You can compile a C# file into an assembly using the C#
compiler csc:
csc /target:library MyLibrary.cs
using MyLibrary;
class Program
{
static void Main()
{
MyLibraryClass obj = new MyLibraryClass();
obj.PrintMessage();
}
}
Assembly Versioning:
• Assemblies can have versions, which helps in managing updates and compatibility.
• Example of versioning:
Types of Collections
1. Array:
2. List:
– Syntax:
3. Dictionary<TKey, TValue>:
– Syntax:
4. Queue:
5. Stack:
– Syntax:
Collection Methods
• Common methods used with collections include:
– Add(): Adds an element.
– Remove(): Removes an element.
– Contains(): Checks if an element exists.
– Clear(): Removes all elements.
– Count: Returns the number of elements.
Enumerations
What is an Enumeration?
• An enumeration (enum) is a special value type that defines a set of named
constants.
• Enums are used when you need a predefined set of values, like days of the week or
directions.
Declaring an Enum
• Enums are declared using the enum keyword.
• Syntax:
enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
enum Days
{
Sunday = 1,
Monday = 2,
Tuesday = 3
}
• Using Enums:
– Example:
switch (today)
{
case Days.Monday:
Console.WriteLine("Start of the work week.");
break;
case Days.Sunday:
Console.WriteLine("It's the weekend!");
break;
}
• Enum Methods:
– Example:
• Syntax:
dt.Rows.Add(1, "John");
dt.Rows.Add(2, "Jane");
• Example:
Exception Types
• Exception: The base class for all exceptions.
• Common derived classes include:
– System.NullReferenceException: Thrown when you try to access a null
object.
– System.IO.IOException: Thrown when an I/O error occurs (file not
found, etc.).
– System.DivideByZeroException: Thrown when attempting to divide by
zero.
Throwing Exceptions
• You can manually throw exceptions using the throw keyword:
if (age < 0)
{
throw new ArgumentOutOfRangeException("Age cannot be
negative.");
}
try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero.");
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
Finally Block
• The finally block is optional and runs after the try and catch blocks, regardless
of whether an exception was thrown.
try
{
// Code
}
catch (Exception ex)
{
// Handle exception
}
finally
{
// Code that always runs (e.g., cleanup code)
}
Custom Exceptions
• You can create custom exceptions by inheriting from the Exception class.
• Example usage:
1. Console Application
• Description: A console application is a simple application that runs in a command-
line environment. It’s a text-based interface where the user interacts with the
application through the console window.
• Uses: Suitable for utilities, learning programming basics, or backend processing.
• Example: Simple calculators, command-line tools.
5. Class Library
• Description: A class library project is a collection of classes and functions that can
be used by other applications.
• Uses: Creating reusable libraries that can be shared across different applications.
• Example: Utility libraries, frameworks, or custom class libraries for an application.
6. Xamarin Application
• Description: Xamarin is used for building mobile applications for Android, iOS, and
Windows using a single C# codebase.
• Uses: Cross-platform mobile applications.
• Example: Mobile apps like social media clients, task management apps.
7. Azure Functions
• Description: Azure Functions allows you to run small pieces of code (functions) in
the cloud without having to manage the underlying infrastructure.
• Uses: Serverless applications, cloud-triggered functions.
• Example: Event-driven applications that respond to cloud events.
8. Blazor Application
• Description: Blazor is a framework for building interactive web UIs using C#
instead of JavaScript. It can run on the client-side via WebAssembly or server-side.
• Uses: Interactive web applications with C# on both server and client sides.
• Example: Web-based dashboards, e-commerce platforms.
• UtcNow: Gets the current date and time in UTC (Coordinated Universal Time).
• Today: Gets the current date with the time set to midnight.
2. Writing Files:
• StreamWriter: Used to write text to a file.
3. File Existence:
• File.Exists(): Checks if a file exists.
4. Copying Files:
• File.Copy(): Copies a file to a new location.
File.Copy("source.txt", "destination.txt");
5. Deleting Files:
• File.Delete(): Deletes a specified file.
File.Delete("file.txt");
Project Structure:
/EmptyWebApp
├── /App_Data
├── /Content
├── /Scripts
├── /Views
├── Global.asax
├── Web.config
<script runat="server">
void Application_Start(object sender, EventArgs e) {
// Code that runs on application startup
}
</script>
2. Web.config:
– Configuration file for the web application, like database connection strings,
routing, and security settings.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<!-- Your app settings -->
</appSettings>
<connectionStrings>
<!-- Your connection strings -->
</connectionStrings>
</configuration>
Project Structure:
/WebFormsApp
├── /App_Data
├── /Content
├── /Scripts
├── /Pages
│ └── Default.aspx
├── Global.asax
├── Web.config
Key Files:
1. Default.aspx:
– A typical Web Forms page containing HTML markup and server controls.
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
Inherits="WebFormsApp._Default" %>
<html>
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" ID="Label1" Text="Hello, Web
Forms!" />
<asp:Button runat="server" Text="Click Me"
OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
2. Default.aspx.cs:
– The code-behind file where you handle server-side logic, such as button
clicks.
using System;
namespace WebFormsApp
{
public partial class _Default : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Button clicked!";
}
}
}
Project Structure:
/MvcApp
├── /Controllers
│ └── HomeController.cs
├── /Models
│ └── WeatherForecast.cs
├── /Views
│ └── /Home
│ └── Index.cshtml
├── Global.asax
├── Web.config
Key Files:
1. HomeController.cs:
– The controller that handles HTTP requests and returns appropriate views.
using System.Web.Mvc;
namespace MvcApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new WeatherForecast { Date = "2024-11-
27", Summary = "Sunny", TemperatureC = 22 };
return View(model);
}
}
}
2. Index.cshtml:
– The Razor view that represents the HTML page for the Index action.
@model MvcApp.Models.WeatherForecast
<h1>Weather Forecast</h1>
<p>Date: @Model.Date</p>
<p>Temperature: @Model.TemperatureC °C</p>
<p>Summary: @Model.Summary</p>
3. Web.config:
Project Structure:
/WebAPIApp
├── /Controllers
│ └── WeatherController.cs
├── /Models
│ └── WeatherForecast.cs
├── Global.asax
├── Web.config
Key Files:
1. WeatherController.cs:
– The API controller that handles HTTP requests and returns data in JSON
format.
using System.Collections.Generic;
using System.Web.Http;
namespace WebAPIApp.Controllers
{
public class WeatherController : ApiController
{
public IEnumerable<WeatherForecast> Get()
{
return new List<WeatherForecast>
{
new WeatherForecast { Date = "2024-11-27",
TemperatureC = 20, Summary = "Sunny" },
new WeatherForecast { Date = "2024-11-28",
TemperatureC = 15, Summary = "Cloudy" }
};
}
}
}
2. WeatherForecast.cs (Model):
namespace WebAPIApp.Models
{
public class WeatherForecast
{
public string Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
}
}
Project Structure:
/SPAApp
├── /ClientApp (Angular/React/Vue)
├── /Controllers
│ └── ApiController.cs
├── Web.config
Key Files:
1. ApiController.cs (Web API Controller):
using System.Collections.Generic;
using System.Web.Http;
namespace SPAApp.Controllers
{
public class ApiController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "Value1", "Value2" };
}
}
}
2. Web.config:
– Configuration settings, including API routes and security for the back-end.
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.7.2" />
</system.web>
</configuration>