1.
Introduction to C#
C# (pronounced "C-sharp") is a versatile, object-oriented programming language developed
by Microsoft. It was designed to be simple, modern, and suitable for a variety of applications,
including web, desktop, and mobile development. C# is part of the .NET framework and is
widely used for enterprise applications.
2. Common Language Runtime (CLR)
The Common Language Runtime (CLR) is the execution engine for .NET programs. It
provides key services such as memory management, type safety, exception handling, garbage
collection, and security.
Memory Management: The CLR automatically manages the allocation and release of
memory for objects, which reduces the chances of memory leaks and improves
efficiency.
Garbage Collection: The CLR includes a garbage collector that automatically
deallocates memory that is no longer in use by the application.
Security: The CLR enforces code access security (CAS) and provides a layer of
abstraction that prevents low-level access to the system, ensuring that code runs in a
safe environment.
Exception Handling: The CLR provides a structured mechanism for handling runtime
errors, ensuring that exceptions can be caught and managed appropriately.
3. Visual Studio and Console Applications
Visual Studio is a powerful integrated development environment (IDE) from Microsoft. It
supports multiple programming languages, including C#, and provides a range of tools for
writing, debugging, and deploying code.
Features of Visual Studio:
o IntelliSense: Autocompletion and context-aware suggestions while typing
code.
o Debugger: Powerful tools for setting breakpoints, inspecting variables, and
stepping through code.
o Project Templates: Predefined templates for different types of applications,
such as Console Apps, Windows Forms, and ASP.NET applications.
o Integrated Source Control: Supports Git, SVN, and other version control
systems directly within the IDE.
Console Applications:
Console Application: A type of application that runs in a command-line interface
(CLI) and interacts with the user via text input and output.
Creating a Console Application: In Visual Studio, you can create a console application
by selecting the appropriate project template, writing your code in the Main method,
and running the application to see the output in the console window.
Example:
using System;
namespace HelloWorldApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
4. C# Language Fundamentals
4.1. Data Types
C# is a strongly-typed language, meaning that each variable must be declared with a specific
data type. This ensures that the type of data a variable can hold is defined at compile time.
Value Types: These types store the actual data. Examples include int, double, bool,
and char. Value types are typically stored on the stack.
o Integer Types: int, long, short, byte
o Floating-Point Types: float, double, decimal
o Boolean: bool (can hold true or false)
o Character: char (stores a single 16-bit Unicode character)
Reference Types: These types store references (or pointers) to the actual data.
Examples include string, arrays, classes, and objects. Reference types are typically
stored on the heap.
o String: Represents a sequence of characters.
o Array: A collection of elements of the same type.
o Class: A blueprint for creating objects.
Example:
int age = 25;
double salary = 50000.50;
bool isMarried = false;
char grade = 'A';
string name = "Alice";
4.2. Variables and Constants
Variables: Variables are used to store data that can change during the execution of a
program. In C#, a variable must be declared with a specific type.
Example:
int score = 95;
string playerName = "John";
Constants: Constants are used to store data that does not change during the execution
of a program. Constants are declared using the const keyword.
Example:
const double Pi = 3.14159;
const int DaysInWeek = 7;
4.3. Operators
C# includes a variety of operators for performing operations on variables and values.
Arithmetic Operators: +, -, *, /, %
o Example:
int sum = 10 + 5; // 15
int product = 4 * 5; // 20
int remainder = 10 % 3; // 1
Comparison Operators: ==, !=, <, >, <=, >=
Example:
bool isEqual = (5 == 5); // true
bool isGreater = (10 > 5); // true
Logical Operators: &&, ||, !
Example:
result = (5 > 3) && (10 < 20); // true
Assignment Operators: =, +=, -=, *=, /=
o Example:
int x = 10;
x += 5; // x is now 15
4.4. Control Structures
Control structures allow you to control the flow of execution in a program based on certain
conditions.
Conditional Statements: Used to perform different actions based on different
conditions.
o if, else if, else
Example:
int number = 10;
if (number > 0)
{
Console.WriteLine("Positive number");
}
else if (number < 0)
{
Console.WriteLine("Negative number");
}
else
{
Console.WriteLine("Zero");
}
o switch: An alternative to multiple if-else statements, used for selecting one of
many code blocks to execute.
Example:
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Other day");
break;
}
Loops: Used to execute a block of code repeatedly as long as a specified condition is
true.
o for, while, do-while, foreach
Example:
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Value of i: " + i);
}
int j = 0;
while (j < 5)
{
Console.WriteLine("Value of j: " + j);
j++;
}
4.5. Methods
Methods are blocks of code that perform a specific task. They help in organizing and reusing
code.
Method Declaration: Defines the method’s name, return type, and parameters.
Example:
void Greet(string name)
{
Console.WriteLine("Hello, " + name);
}
Greet("Alice");
Return Types: A method can return a value or be void if it does not return anything.
Example:
int Add(int a, int b)
{
return a + b;
}
int result = Add(5, 3); // result is 8
Method Overloading: Allows multiple methods to have the same name but different
parameters.
Example:
void Print(int number)
{
Console.WriteLine(number);
}
void Print(string text)
{
Console.WriteLine(text);
}
Examples:
Here's a C# program that uses a structure to store and display information about a
book, including its title, author, and price:
using System;
namespace BookInfoApp
{
// Define a structure to store book information
struct Book
{
public string Title;
public string Author;
public double Price;
// Constructor to initialize the structure
public Book(string title, string author, double price)
{
Title = title;
Author = author;
Price = price;
}
// Method to display book information
public void DisplayInfo()
{
Console.WriteLine("Book Information:");
Console.WriteLine($"Title: {Title}");
Console.WriteLine($"Author: {Author}");
Console.WriteLine($"Price: ${Price:F2}");
}
}
class Program
{
static void Main(string[] args)
{
// Create a Book structure instance and initialize it
Book myBook = new Book("1984", "George Orwell", 19.99);
// Display the book information
myBook.DisplayInfo();
// Wait for user input before closing the console window
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
Common Language Runtime (CLR):
CLR provides a framework for developing and deploying .NET applications, including a set
of libraries, called the .NET Framework Class Library, which provides access to a wide range
of functionality, such as input/output operations, networking, database connectivity, and user
interface design.
Overall, the CLR is a critical component of the .NET Framework and is responsible for
ensuring that .NET applications are executed in a safe, secure, and efficient manner, making
it a fundamental aspect of C# programming.
CLR is the basic and Virtual Machine component of the .NET Framework. It is the run-time
environment in the .NET Framework that runs the codes and helps in making the
development process easier by providing the various services. Basically, it is responsible for
managing the execution of .NET programs regardless of any .NET programming language.
Internally, CLR implements the VES(Virtual Execution System) which is defined in the
Microsoft’s implementation of the CLI(Common Language Infrastructure).
The code that runs under the Common Language Runtime is termed as the Managed Code. In
other words, you can say that CLR provides a managed execution environment for
the .NET programs by improving the security, including the cross language integration and a
rich set of class libraries, etc. CLR is present in every .NET framework version. Below table
illustrate the CLR version in .NET framework.
CLR Versions .NET Framework Versions
1.0 1.0
1.1 1.1
2.0 2.0
2.0 3.0
2.0 3.5
4 4
4 4.5(also 4.5.1 & 4.5.2)
4 4.6(also 4.6.1 & 4.6.2)
4 4.7(also 4.7.1 & 4.7.2)
Below diagram illustrate how CLR is associated with the operating system/hardware along
with the class libraries. Here, the runtime is actually CLR.
Role of CLR in the execution of a C# program
Suppose you have written a C# program and save it in a file which is known as the
Source Code.
Language specific compiler compiles the source code into the MSIL(Microsoft
Intermediate Language) which is also known as the CIL(Common Intermediate
Language) or IL(Intermediate Language) along with its metadata. Metadata includes
all the types, actual implementation of each function of the program. MSIL is
machine-independent code.
Now CLR comes into existence. CLR provides the services and runtime environment
to the MSIL code. Internally CLR includes the JIT(Just-In-Time) compiler which
converts the MSIL code to machine code which further executed by CPU. CLR also
uses the .NET Framework class libraries. Metadata provides information about the
programming language, environment, version, and class libraries to the CLR by which
CLR handles the MSIL code. As CLR is common so it allows an instance of a class
that written in a different language to call a method of the class which written in
another language.
Main Components of CLR
As the word specify, Common means CLR provides a common runtime or execution
environment as there are more than 60 .NET programming languages.
Main components of CLR:
Common Language Specification (CLS):
It is responsible for converting the different .NET programming language syntactical rules
and regulations into CLR understandable format. Basically, it provides Language
Interoperability. Language Interoperability means providing execution support to other
programming languages also in .NET framework.
Language Interoperability can be achieved in two ways :
1. Managed Code: The MSIL code which is managed by the CLR is known as the
Managed Code. For managed code CLR provides three .NET facilities:
2. Unmanaged Code: Before .NET development, programming languages like.COM
Components & Win32 API do not generate the MSIL code. So these are not managed
by CLR rather managed by Operating System.
Common Type System (CTS):
Every programming language has its own data type system, so CTS is responsible for
understanding all the data type systems of .NET programming languages and converting
them into CLR understandable format which will be a common format.
Garbage Collector:
It is used to provide the Automatic Memory Management feature. If there was no garbage
collector, programmers would have to write the memory management codes which will be a
kind of overhead on programmers.
JIT(Just In Time Compiler):
It is responsible for converting the CIL(Common Intermediate Language) into machine code
or native code using the Common Language Runtime environment.
Enumeration (or enum) is a value data type in C#. It is mainly used to assign the names or
string values to integral constants, that make a program easy to read and maintain. For
example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond,
Heart, and Spade, belonging to an enumerated type named Suit. Other examples include
natural enumerated types (like the planets, days of the week, colors, directions, etc.). The
main objective of enum is to define our own data types(Enumerated Data Types).
Enumeration is declared using enum keyword directly inside a namespace, class, or structure.
Syntax:
enum Enum_variable
{
string_1...;
string_2...;
.
.
}
In above syntax, Enum_variable is the name of the enumerator, and string_1 is attached with
value 0, string_2 is attached value 1 and so on. Because by default, the first member of an
enum has the value 0, and the value of each successive enum member is increased by 1. We
can change this default value.
Example 1: Consider the below code for the enum. Here enum with name month is
created and its data members are the name of months like jan, feb, mar, apr, may. Now
let’s try to print the default integer values of these enums. An explicit cast is
required to convert from enum type to an integral type.
C#
// C# program to illustrate the enums
// with their default values
using System;
namespace ConsoleApplication1 {
// making an enumerator 'month'
enum month
{
// following are the data members
jan,
feb,
mar,
apr,
may
class Program {
// Main Method
static void Main(string[] args)
{
// getting the integer values of data members..
Console.WriteLine("The value of jan in month " +
"enum is " + (int)month.jan);
Console.WriteLine("The value of feb in month " +
"enum is " + (int)month.feb);
Console.WriteLine("The value of mar in month " +
"enum is " + (int)month.mar);
Console.WriteLine("The value of apr in month " +
"enum is " + (int)month.apr);
Console.WriteLine("The value of may in month " +
"enum is " + (int)month.may);
}
}
}
C# | Namespaces
Last Updated : 01 Feb, 2019
Namespaces are used to organize the classes. It helps to control the scope of methods and
classes in larger .Net programming projects. In simpler words you can say that it provides a
way to keep one set of names(like class names) different from other sets of names. The
biggest advantage of using namespace is that the class names which are declared in one
namespace will not clash with the same class names declared in another namespace. It is also
referred as named group of classes having common features. The members of a namespace
can be namespaces, interfaces, structures, and delegates.
Defining a Namespace
To define a namespace in C#, we will use the namespace keyword followed by the name of
the namespace and curly braces containing the body of the namespace as follows:
Syntax:
namespace name_of_namespace {
// Namespace (Nested Namespaces)
// Classes
// Interfaces
// Structures
// Delegates
}
Example:
// defining the namespace name1
namespace name1
{
// C1 is the class in the namespace name1
class C1
{
// class code
}
}
Accessing the Members of Namespace
The members of a namespace are accessed by using dot(.) operator. A class in C# is fully
known by its respective namespace.
Syntax:
[namespace_name].[member_name]
Structure
is a value type and a collection of variables of different data types under a single unit. It is
almost similar to a class because both are user-defined data types and both hold a bunch of
different data types. C# provide the ability to use pre-defined data types. However,
sometimes the user might be in need to define its own data types which are also known
as User-Defined Data Types. Although it comes under the value type, the user can modify it
according to requirements and that’s why it is also termed as the user-defined data type.
Defining Structure: In C#, structure is defined using struct keyword. Using struct keyword
one can define the structure consisting of different data types in it. A structure can also
contain constructors, constants, fields, methods, properties, indexers and events etc.
Syntax:
Access_Modifier struct structure_name
{
// Fields
// Parameterized constructor
// Constants
// Properties
// Indexers
// Events
// Methods etc.
}
Example:
CSHARP
// C# program to illustrate the
// Declaration of structure
using System;
namespace ConsoleApplication {
// Defining structure
public struct Person
{
// Declaring different data types
public string Name;
public int Age;
public int Weight;
class Geeks {
// Main Method
static void Main(string[] args)
{
// Declare P1 of type Person
Person P1;
// P1's data
P1.Name = "Keshav Gupta";
P1.Age = 21;
P1.Weight = 80;
// Displaying the values
Console.WriteLine("Data Stored in P1 is " +
P1.Name + ", age is " +
P1.Age + " and weight is " +
P1.Weight);
}
}
}