0% found this document useful (0 votes)
2 views

intro to c#

The document provides an overview of C#, a modern, object-oriented programming language developed by Microsoft, highlighting its goals, features, and syntax. It covers the language's history, key features such as garbage collection and type safety, and provides examples of basic programming concepts including class declarations, data types, and decision-making statements. The document also includes practical examples of code execution and the use of namespaces, command line arguments, and user input.

Uploaded by

24250155nikesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

intro to c#

The document provides an overview of C#, a modern, object-oriented programming language developed by Microsoft, highlighting its goals, features, and syntax. It covers the language's history, key features such as garbage collection and type safety, and provides examples of basic programming concepts including class declarations, data types, and decision-making statements. The document also includes practical examples of code execution and the use of namespaces, command line arguments, and user input.

Uploaded by

24250155nikesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Overview

• Goals of C#
• Brief History
• Hello World
• Syntax
• Features
• Type System
Goals of C#

• A simple, modern, general-purpose object-oriented


language.
• Software robustness and programmer productivity
– Strong type checking, array bounds checking, detection
of use of uninitialized variables, source code portability,
automatic garbage collection
• Useable in creating software components
• Ease of learning by programmers familiar with C++ and Java
• Usable for embedded and large system programming
• Strong performance, but not intended to compete with C
or assembly language
Brief History

• Originated by Microsoft as a response to Java


– Initial public release in 2000

• Language name inspired by musical note C#


– A “step above” C/C++ (and Java)
• Lead designers: Anders Hejlsberg, Scott Wiltamuth

• C# standardized via ECMA and ISO


– However, Microsoft retains architectural control
Features

• C# is a simple , modern, object oriented language derived from


C++ and Java.
• It aims to combine the high productivity of Visual Basic and the
raw power of C++.
• IDE Microsoft Visual Studio.(latest version - Visual Studio 2022
version 17.8)
• Visual studio supports VB , VC++,C++, VBScript, Jscript . All of
these languages provide access to the Microsoft .NET platform.
• .NET includes a Common Execution engine and a rich class
library.
• The following reasons make C# a widely used professional
language:
• Modern, general-purpose programming language
• Object oriented.
• Component oriented.
• Easy to learn.
• Structured language.
• It produces efficient programs.
• It can be compiled on a variety of computer platforms.
• Part of .NET Framework
• CLR accommodates more than one languages such as C#, VB.NET,
Jscript,ASP.NET,C ++.

• Source code --->Intermediate Language code(IL) ---> (JIT Compiler) Native


code.

• The classes and data types are common to all of the .NET languages.

• We may develop Console application , Windows application , Web


application using C#.

• In C# Microsoft has taken care of C++ problems such as Memory


management,pointers etc.

• It support garbage collection, automatic memory management.



Latest version of C# is C# 13.0, which was released in 2024 in .NET 9.
Key Features

• C# is a simple, modern, object oriented language derived


from C++ and Java.
• It aims to combine the high productivity of Visual Basic and
the raw power of C++.
• Provides all features of the Microsoft .NET platform
including Garbage Collection.
• The classes and data types are common to all of the .NET
languages.
• Can develop Console application, Windows application, and
Web application using C#.
• In C# Microsoft has taken care of C++ problems such as
automatic Memory management, pointers etc.
MAIN FEATURES OF C#

1. SIMPLE
2. MODERN
3. OBJECT ORIENTED
4.TYPE SAFE
5.INTEROPERABILITY
6.SCALABLE AND UPDATEABLE

CONCLUSION
• C# is a modern, type safe programming language, object
oriented language that enables programmers to quickly and
easily build solutions for the Microsoft .NET platform
Hello World !!!

using System;
class Hello
{
static void Main()
{
Console.WriteLine(“Hello, World!”);
}
}
Hello World !!!

Class Declaration:
• “Class Hello “ declares a class, which is an object-oriented
construct.
• Since C# is an OOP Language, Everything must be placed
inside a class.
• A class is like a template for what an object looks like and
how it behaves.
• C# is a block-structured language which means code blocks
are always enclosed by braces { and }.
Hello World !!!

The Main Method

• “public static void Main()” defines a method named Main.


• Every C# program must include the Main() method in one
of the classes.
• This is the starting point for the execution of the program.
• A C# program can have any number of classes but only one
class with the Main method.
Hello World !!!

The Main Method

• public: An access modifier that tells the C# compiler that


the Main method is accessible by anyone.
• static: It declares that the Main method is a global one and
can be called without creating an instance of the class.
• void: It is a type modifier that states that the Main method
does not return any value.
Hello World !!!

The Output:

System.Console.WriteLine(“Hello, World!”);
• Since C# is pure OOP Language, every method should be
part of an object.
• The WriteLine method is a static method of the Console
class, which is located in the namespace called System.
Syntax

• Case-sensitive
• Every Statement should end with a semicolon.
• Curly braces {} enclose code blocks
• Whitespace has no meaning
– Sequences of space, tab, linefeed, carriage return
• Comments:
– /* comment */
– // comment
Executing the Program

File Name To Compile To Execute

Hello.class
Hello.java javac Hello.java java Hello

Hello.exe
Hello.cs csc Hello.cs Hello
Name Spaces in C#

• A namespace in C++ and C# is a way to group functionality


into packages.
• A class in a namespace can be accessed using the dot
operator.
• Namespaces are the way in which C# segregates the .NET
library classes into reasonable groupings.
• The using directive is used to import the namespaces.
• Once a namespace is imported, we can use the elements of
that namespace without using the namespace as prefix.
using System;
namespace first_space
{
class firstclass
{
public void func()
{
Console.WriteLine("Inside first_space");
}
}
}
namespace second_space
{
class secondclass
{
public void func()
{
Console.WriteLine("Inside second_space");
}
}
}
class TestClass
{
static void Main(string[] args)
{
first_space.firstclass fc = new
first_space.firstclass();
second_space.secondclass sc = new
second_space.secondclass();
fc.func();
sc.func();
Console.ReadKey();
}
}
using System;
using first_space;
using second_space;

namespace first_space
{
class abc {
public void func()
{
Console.WriteLine("Inside first_space");
}
}
}
namespace second_space
{
class efg
{
public void func()
{
Console.WriteLine("Inside second_space");
}
}
}
class TestClass
{
static void Main(string[] args)
{
abc fc = new abc();
efg sc = new efg();
fc.func();
sc.func();
Console.ReadKey();
}
}
using System;
using first_space;
using first_space.second_space;

namespace first_space {
class abc {
public void func() {
Console.WriteLine("Inside first_space");
}
}
namespace second_space {
class efg {
public void func() {
Console.WriteLine("Inside second_space");
}
}
}
}
class TestClass {
static void Main(string[] args) {
abc fc = new abc();
efg sc = new efg();
fc.func();
sc.func();
Console.ReadKey();
}
}
When the above code is compiled and executed, it
produces the following result −

Inside first_space
Inside second_space
using System;
using first_space;
using nested.second_space;

namespace first_space {
class abc {
public void func() {
Console.WriteLine("Inside first_space");
}
}
}
namespace nested{
namespace second_space {
class efg {
public void func() {
Console.WriteLine("Inside second_space");
}
}
}
Command Line Arguments

• In order to make our program to behave in a particular way


depending on the input provided at the time of execution we
use Command Line Arguments.
• They are parameters supplied to the Main method at the time
of invoking it for execution.
• For Example:
static void Main(string [] args)
{
Console.WriteLine(“Welcome “ + args[0]);
}
Creating Interactive Applications

• Another important Method in the Console Class is the


ReadLine() Method.
• It is used to receive an input from the user while the program
is executing.
• By Default whatever the method receives from the user is
considered as string.
• So, if a particular data type is expected from the user it is
recommended to either use the Convert or Parse Classes.
Example

static void Main()


{
double a,b;
Console.WriteLine("Enter a Number");

a = double.Parse(Console.ReadLine());
Or
a = Convert.ToDouble(Console.ReadLine());
b = Math.Sqrt(a);
Console.WriteLine

(“The Square Root of “ + a + ” is “ + b);


}
Data Types in C#

• Every variable in C# is associated with a data type.


• They specify the size and type of values that can be stored.
• C# Data Types are primarily divided into two categories,
• Value Types
• Reference Types

• They differ in two characteristics:


• Where they are stored in memory.
• How they behave in the context of assignment statements.
Data Types in C#
C# Data Types

Reference
Value Types Types

User-
Predefined User- Predefined Defined
Types Defined Types Types
Types

Integer Enumerations Objects Classes


Boolean Structures Strings Arrays
Characters Delegates
Real Numbers etc. Interfaces
Value Types

• Value Types are of fixed length and are stored on the stack
and when a value of a variable is assigned to another
variable, the value is actually copied.
• Value types of C# can be grouped into two as user-defined
and predefined.
• User-Defined are called complex types which include
struct and enumerations.
• Predefined are called simple types are further subdivided
into Numeric, Boolean and Character types.
• Numeric type includes integral, floating point and decimal
types.
Integral Types

• Integral types can hold whole numbers such as 123, -13,etc.


• Size of the values that can be stored depends on the
integral data type we choose.
• Integral types are further classified as Signed and
Unsigned Integers. Type Size Min Max
• Signed Integers sbyte 1 Byte -128 127
• sbyte,short,int,long short 2 Bytes -32768 32767
• Unsigned Integers int 4 Bytes -2147483648 2147483647
– byte,ushort,uint,ulong long 8 Bytes - 922337203685
922337203685 4775807
4775808
Floating Point Types

• This Type holds numbers containing Fractional parts like


23.13, -12.66 etc.
• There are two types of floating point data types, they are float
and double.
• These numbers are by default are double precision quantities
• To force them to be single precision we must append f to the
numbers. For Eg. 1.23f
Type Size Min Max
float 4 Bytes 1.5 x 10 -45 3.4 x 10 38
double 8 Bytes 5.0 x 10 -324 1.7 x 10 308
Decimal Type

• The Decimal type is a very high precision, 128-bit data type


that is used in financial and monetary calculations.
• It stores values in the range of 1.0 x 10-28 to 7.9 x 1028 with 28
significant digits.
• To specify a number to be Decimal, the character M must be
appended to the value, like 4096.65M.
• If M is omitted then the value is considered as double.
Character and Boolean Types

• Character type stores single characters in Memory and the


data type is called char.
• It assumes a size of 2 Bytes but in fact it can only hold a single
character.

• Boolean type hold only two values true or false.


• The data type is denoted by the keyword bool and uses only
one bit of storage.
• In C#, we cannot use zero as false and non-zero as true since
no conversion between bool type and other types is possible.
Reference Types

• Reference types which are of variable length are stored on the


heap.
• When an assignment between two reference variables occur,
only the reference is copied; the actual value remains in the
same memory location.
• They too have predefined and user-defined types.
• The simple type or predefined has Object type and String
type.
• The user defined or complex type has the following, Classes,
Interfaces, Delegates, Arrays.
Example
Stack and Heap
Declaration of Variables

• Declaring Variables does 3 things


– It tells the compiler what the variable name is.
– It specifies what type of data the variable will hold.
– The place of declaration decides the scope of the variable
• A variable must be declared before it is used.
• The general Syntax of declaring a variable is ,

type var1,var2,…………..var n;
Initialization

• A variable must be given a value after it has been declared.


• The syntax may be of two types,

Type var1 = value;


Or
Type var1;
var1 = value;
Default values

Type Default Value


All Integer Types 0
Char ‘\x000’
Float 0.0f
Double 0.0d
Decimal 0.0m
Bool False
Enum 0
All Reference types null
Boxing and UnBoxing

• In OOP, methods are invoked using objects. Since value


types such as int and long are not objects, we cannot use
them to call methods.

• C# enables us to do so through a technique called Boxing.

• Boxing means the conversion of a value type on the stack


to a object type on the heap.

• Conversely the conversion from an object type back to a


value type is known as Unboxing.
Boxing

• Any Type, value or reference can be assigned to an object


without an explicit conversion.
• When the compiler finds a value type where it needs a
reference type, it creates an object ‘box’ into which it places the
value of that value type.
• For Example:
int m = 10;
object om = m; // Creates a Box to hold m
m=20;
Now the variables m and om exist but the value of om resides on
the heap.
UnBoxing

• It is the process of converting the object type back to the value


type.
• For example:
int m =10;
object om = m; //Box m

int n = (int) om; //Unbox om back to an int

When UnBoxing a value we have to ensure that the value type is


large enough to hold the value of the object.
Operators

• C# supports a rich set of operators. They can be classified into


a number of categories as follows,
1. Arithmetic Operators: +,-,*,/,%
2. Relational Operators: <, <=, >, >=, ==, !=
3. Logical Operators: &&, || , ! , & , | ,^
4. Assignment Operators: a+=1, a-=1, etc.
5. Increment and Decrement Operators: ++ and –
6. Conditional Operators: exp1 ? exp2: exp3
7. Bitwise Operators : ~ , <<, >>
Evaluation of Expressions

• An arithmetic expression without any parentheses will be


evaluated from left to right using the rules of precedence of
operators.
• High Priority: * / %
• Low Priority: + -
• During the first pass the high priority operators are applied as
they are encountered.
• During the second pass the low priority operators are applied
as they are encountered.
• Expressions within parentheses assume highest priority.
• Evaluate : 9-12/3+3*2-1
Decision Making

• C# possesses decision making capabilities and supports the


following statements:
– If statements
• Simple if
• if…else
• Nested if….else
• else if ladder
– Switch statements
– Conditional operator statements
Switch

switch(expression)
{
case value-1:
code block-1
break;
case value-2:
code block-2
break;
…………
default:
default-block
break;
}
Conditional Operator

Condition ? Expression1 : Expression2

For Example
if(x<0)
flag=0;
else
flag=1;
Can be written as
flag = (x<0) ? 0 : 1
Looping Statements

• C# provides four constructs for performing


loop operations.

• The while statement


• The do…while statement
• The for statement
• The foreach statement.
Foreach statement

• The foreach statement is similar to the for statement


but implemented differently.
• This is a special type of for loop which enables us to
iterate through the elements in arrays and collection
classes such as list and hashtables.
• Syntax:
foreach ( type variable in expression)
{
//body of the loop
}
Foreach statement

• Example:
int[] myArray = {1,2,3,4,5};
foreach(int m in myArray)
{
Console.WriteLine(m);
}
Handling Arrays

• An array is a group of contiguous or related data items


that share a common name and refers to those items
by specifying a index value.
• To create an array,
• Declaring the array
• Creating memory locations
• Putting values into the memory locations
• Syntax
type arrayName = new type[size];
Handling Arrays

• To Declare an Array
type [] arrayname;
e.g. int[] myArray;

• To create memory location


arrayname = new type[size];
e.g. myArray = new int[5];

• To put values in the array


Arrayname[index]= value;
myArray[2] = “13”;
Handling Arrays

• We can also initialize and assign values easily by using the


following syntax.
type [] arrayname={ list of values};
e.g.
int[] number = {1,2,3,4,5};
This is also equivalent to
int [] number = new int [5] {1,2,3,4,5};
System.Array Class

• In C# every array we create is derived from System.Array Class.


• This class has a number of methods and properties that can be
used to manipulate arrays more efficiently.
• Few Examples:
• Length - Gives the Length of the Array.
• Sort() - Sorts the elements in an 1-D array.
• Reverse() - Reverse the contents of an 1-D array.
• CopyTo() - Copies elements from source array to
destination array.
• Clear() - Sets all the elements to empty values.
ArrayList Class

• System.Collections namespace defines a class known as


ArrayList that can store a dynamically sized array of objects.
• It includes a number of methods to support operations such as
sorting, removing and enumerating its contents.
• Syntax:
ArrayList cities = new ArrayList(30);
• This will create a cities list with the capacity of 30 and by
default it has size as 16.
• To add elements to this list,
cities.Add(“Chennai”);
cities.Add(“Mumbai”);
Methods in C#

• In OOP objects are used as building blocks in developing a


program.
• Objects encapsulate data and code to manipulate that data.
• The code designed to work on the data is known as methods
in C#.
• In C# every method must be contained within a class.
• Syntax:
modifiers type method-name (formal parameter list)
{
//Method Body
}
Methods in C#

• Once methods are defined they can be invoked using the


following syntax.
objectname.methodname(actual parameter list);
Example
Class cubeClass
{
int cube(int x)
{
return x*x*x;
}
}
Methods in C#

• To use the previous method ,


class CubeTest
{
public static void Main()
{
cubeClass c = new cubeClass();
int y = c.cube(3);
Console.WriteLine(y);
}
}
Object Oriented Programming

• C# is an true Object-Oriented and therefore the underlying


structure of all C# programs is classes.

• Anything we wish to represent in a C# program must be


encapsulated in a class that defines the state and behavior of
the basic program components known as objects.

• Classes create Objects and Objects use methods to


communicate between them.

• This is Object Oriented Programming.


Basic Principles of OOP

• All Object Oriented Languages employ three


core principles, namely,

– Polymorphism
– Inheritance
– Encapsulation

These are often referred to as three pillars of OOP.


Encapsulation

• It provides the ability to hide the internal details of an object


from its users.

• The outside user may not be able to change the state of an


object directly.

• In C# encapsulation is implemented using access modifier


keywords public, private and protected.

• The concept of encapsulation is also known as data hiding or


information hiding.
Inheritance

• It’s the concept we use to build new classes using the existing
class definitions.
• Through inheritance we can modify a class the way we want to
create new objects.
• The original class is known as base or parent class and the
modified one is known as derived class or subclass or child
class.
• The concept of inheritance facilitates the reusability of
existing code and thus improves the integrity of programs and
productivity of programmers.
Types of Inheritance

• Single Inheritance. A B

(Only one Base Class) B


• Hierarchical Inheritance. A C
(One Base Class, many Subclasses)
D

• Multilevel Inheritance.
A B C
(Derived from a derived class)

A
• Multiple Inheritance. C

(Several base classes) B


Polymorphism

• Polymorphism means “One name, many


forms”.
• Essentially polymorphism is the capability of
one object to behave in multiple ways.
• Polymorphism can be achieved in two ways ,
– Operation Polymorphism.
-Using Overloaded Methods.

– Inclusion Polymorphism
- Using Virtual Methods
Exception Handling

• Errors are mistakes that may produce incorrect


output or may terminate the execution of the
program abruptly or even may cause the system to
crash.

• Errors may be broadly classified into two categories:

– Compile Time Errors.


– Run-Time Errors.
Compile Time errors

• Missing Semicolons
• Missing or mismatch of Brackets in classes and
methods.
• Misspelling of identifiers and keywords.
• Missing double quotes in strings.
• Use of undeclared variables.
• Incompatible types in assignments / initialization.
• Bad references to objects.
• Use of = in the place of == , etc..
Run Time errors

• Dividing an Integer by zero.


• Accessing an element that is out of the bounds of an array.
• Trying to store a value into an array of an incompatible class or
type.
• Passing parameter that is not in a valid range or value for a
method.
• Attempting to use a negative size for an array.
• Using a null object reference as a legitimate object reference to
access a method or a variable.
• Converting an invalid string to a number or vice versa.
• Accessing a character that is out of bounds of a string, etc..
Exceptions

• An exception is a condition that is caused by a run-time error


in a program.
• When the C# compiler encounters an error such as dividing an
integer by zero, it creates an exception object and throws it.
• If the exception object is not caught and handled properly, the
compiler will display an error message and will terminate the
program.
• If we want the program to continue with the execution of the
remaining code, then we should try to catch the exception
object thrown by the error condition and then display an
appropriate message for taking corrective actions.
• This task is known as exception handling.
Exception Handling

• The purpose of the exception handling mechanism is


to provide a means to detect and report an
“Exceptional Circumstance” so that appropriate
action can be taken.
• This suggests a separate error handling code that
performs the following tasks:
– Find the problem(Hit the exception)
– Inform that an error has occurred(Throw the exception)
– Receive the error information(Catch the exception)
– Take corrective actions(Handle the exception)
Some C# Exceptions

Exception Class Cause of exception

ArgumentException An argument to a method was invalid

ArithmeticException Arithmetic Over or underflow has occurred.

DividebyZeroException An attempt was made to divide by zero

IndexOutOfRangeException An array index is out of bounds

NullReferenceException Attempt to use an unassigned reference

OutofMemoryException Not enough memory to continue execution

StackOverflowException A Stack has overflowed.


Some C# Exceptions
try
{
//Block of code;
}
catch(exception 1)
{
…….
}
finally
{
…….
}
Throwing our own Exceptions

• We can throw our own exceptions.


• But Exception must be the ultimate base class for all
exceptions in C#.
• So the user-defined exception classes must inherit from either
Exception class or one of its standard derived classes.
• We can do this by using the keyword throw as follows.
Throw new Throwable_Subclass;
Examples:
throw new ArithmeticException();
throw new FormatException();
Garbage Collection

• Every program uses resources of one sort or another memory


buffers, network connections, database resources and so on.

• In OOP, every type identifies some resource available for a


program’s use.

• To use any of these resources, memory must be allocated to


represent the type.

• The GC in .NET completely absolves the developer from


tracking memory usage and knowing when to free memory
Garbage Collection

• The Microsoft CLR requires that all resources be allocated


from the managed heap.
• The free-objects from the managed heap are automatically
freed when they are no longer needed by the application.
• The GC must perform a collection in order to free some
memory.
• The GC’s optimizing engine determines the best time to
perform a collection, based upon the allocations made.
• When GC performs a collection, It checks for objects in the
managed heap that are no longer being used by the
application and performs the necessary operations to reclaim
their memory.
Implementation of GC

• Garbage Collection in .NET is done using tracing collection


and specifically the CLR implements the following two
phases,

• Phase I –Mark.

• Phase II – Compact.
Phase – I Mark

• Find Memory that can be reclaimed.


• Steps involved in Phase I.
– The GC identifies live object references or application
roots.
– It starts from the roots and builds a graph of all objects
reachable from the roots.
– If the GC attempts to add an object already present in the
graph, then it stops.
• This serves 2 purposes.
1. Helps performance significantly
2. Prevents infinite Loops.
Phase – II Compact

• Moves all the live objects to the bottom of the heap, leaving free
space at the top.
• It includes,
– GC walks through the heap linearly, looking for contiguous
blocks of garbage objects.
– It then shifts the non-garbage objects down in memory,
removing all of the gaps in the heap.
– Moving objects in memory, invalidates all pointers to the
objects, so GC modifies the apps root so that the pointers
point to the objects new location.
– In addition, if any object contains a pointer to another object,
the GC is responsible for correcting these pointers as well.
Delegates

• Basically it is similar like the “C” function pointer, where


functions can be assigned like variables and called in the run
time based on dynamic conditions.
• C# delegate is the smarter version of function pointer.
• At first, a delegate is defined with a specific signature (return
type, parameter type and order etc).
• To invoke a delegate object, one or more methods are required
with the EXACT same signature.
• A delegate object is created, like how a class object is created.
• The delegate object will basically hold a reference of a function.
• The function can then be called via the delegate object.
Delegates

With an example:

1. Defining the delegate

public delegate int Calculate(int value1, int value2);


Delegates

2. Creating methods which will be assigned to delegate object


/*A method, that will be assigned to delegate objects
having the EXACT signature of the delegate */
public int add(int value1, int value2)
{
return value1 + value2;
}
public int sub(int value1, int value2)
{
return value1 - value2;
}
Delegates

3. Creating the delegate object and assigning methods to


those delegate objects
/*creating the class which contains the methods that will be
assigned to delegate objects */
MyClass mc = new MyClass();

/*creating delegate objects and assigning appropriate methods


having the EXACT signature of the delegate */

Calculate add = new Calculate(mc.add);


Calculate sub = new Calculate(mc.sub);
Delegates

4. Calling the methods via delegate objects

/* using the delegate objects to call the assigned methods */

Console.WriteLine("Adding two values: " + add(10, 6));

Console.WriteLine("Subtracting two values: " + sub(10,4));


Preprocessors

• While the compiler does not have a separate preprocessor,


the directives described in this section are processed as if
there was one; these directives are used to aid in conditional
compilation.
• Unlike C and C++ directives, you cannot use these directives
to create macros.
• A preprocessor directive must be the only instruction on a
line.
• Some of the pre processor directives are #if, #else, #elif,
#endif, #define, #undef, #warning, #error, #line, #region,
#endregion.
Preprocessor

• #define and #undef, which are used to define and undefine,


respectively, conditional compilation symbols.
• #if, #elif, #else, and #endif, which are used to conditionally
skip sections of source code.
• #line, which is used to control line numbers emitted for
errors and warnings.
• #error and #warning, which are used to issue errors and
warnings, respectively.
• #region and #endregion, which are used to explicitly mark
sections of source code.
Preprocessor

#define DEBUG
#define VC_V7
using System;
public class MyClass
{ public static void Main()
{
#if (DEBUG && !VC_V7)
Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V7)
Console.WriteLine("VC_V7 is defined");
#elif (DEBUG && VC_V7)
Console.WriteLine("DEBUG and VC_V7 are defined");
#else
Console.WriteLine("DEBUG and VC_V7 are not defined");
#endif
}
}
Writing Unsafe code using C#

• The use of pointers is rarely required in C#, but there are


some situations that require them.
• As examples, using an unsafe context to allow pointers is
warranted by the following cases:
• Dealing with existing structures on disk
• Advanced COM or Platform Invoke scenarios that involve
structures with pointers in them
• Performance-critical code
• The use of unsafe context in other situations is discouraged.
Writing Unsafe code using C#

• In unsafe code or in other words unmanaged code it is possible to


declare and use pointers.
• There are some disadvantages of using pointers too.
• If pointers were chosen to be 32 bit quantities at compile time, the
code would be restricted to 4bits of address space, even if it were
run on a 64 bit machine.
• If pointers were chosen at compile time to be 64 bits, the code
could not be run on a 32 bit machine.
• In C# we can write unsafe code with the modifier unsafe.
• All the unsafe code must be clearly marked with the unsafe
modifier.
• Writing unsafe code is much like writing C code in a C# program.
Unsafe Code Example

using System;
class MyClass
{
public static void Main()
{
int iData = 10;
int* pData = &iData;
Console.WriteLine("Data is " + iData);
Console.WriteLine("Address is " (int)pData);
}
Will Produce the following message:
} error CS0214: Pointers may only be used in an unsafe context
Unsafe Code Example
Indicates that
using System; the code block is
class MyClass unsafe

{
public unsafe static void Main()
{
int iData = 10;
int* pData = &iData;
Console.WriteLine("Data is " + iData);
Console.WriteLine("Address is " (int)pData);
} Will Produce the following message:
} Data is 10
Address is 1244316

You might also like