SlideShare a Scribd company logo
Unsafe
• Unsafe code often involves the use of
pointers.
• Unsafe code and pointers enable C# to be
used to create applications that one might
normally associate with C++: highperformance, systems code.
• the inclusion of unsafe code and pointers
gives C# capabilities that are lacking in Java.
• Unsafe code is not code that is poorly written; it
is code that does not execute under the full
management of the common language runtime
(CLR).
• C# is normally used to create managed code.
• It is possible, however, to write code that does
not execute under the full control of the CLR. This
unmanaged code is not subject to the same
controls and constraints as managed code, so it
is called “unsafe”.
• it is not possible to verify that it won’t perform
some type of harmful action.
• Because a pointer can point anywhere in
memory, it is possible to misuse a pointer.
• It is also easy to introduce a coding error
when using pointers. This is why C# does not
support pointers when creating managed
code.
• C# does allow you to create and use pointers.
However, all pointer operations must be
marked as unsafe since they execute outside
the managed context.
Declaring a Pointer
• Pointer variables must be declared as such.
type * var-name ;
• type is the pointer’s referent type.
• var-name is the name of the pointer variable.
• example. To declare ip to be a pointer to an
int, use this declaration:
int* ip;
• If you come from a C/C++ background, then
you need to be aware of an important
difference between the way C# and C/C++
declare pointers.
• When you declare a pointer type in C/C++, the
* is not distributive over a list of variables in
a declaration.
• Thus, in C/C++, this statement
int* p, q;
• in C#, the * is distributive and the declaration
int* p, q;
• creates two pointer variables.
• Thus, in C# it is the same as these two
declarations:
int* p;
int* q;
• Two operators are used with pointers: * and
&.
• The & is a unary operator that returns the
memory address of its operand.
• int* ip;
• int num = 10;
• ip = #
• puts into ip the memory address of the
variable num.
• ip does not contain the value 10.
• The second operator is *, and it is the
complement of &.
• it refers to the value of the variable pointed
to by a pointer.
• ip = #
• int val = *ip;
• will place into val the value 10, which is the
value of num, which is pointed to by ip .
unsafe
• Any code that uses pointers must be marked
as unsafe by using the unsafe keyword.
• You can mark types (such as classes and
structures), members (such as methods and
operators), or individual blocks of code as
unsafe.
• using System;
• class UnsafeCode {
// Mark Main as unsafe.

unsafe static void Main() {
int count = 99;
int* p; // create an int pointer
p = &count; // put address of count into p
Console.WriteLine("Initial value of count is "
+*p);
*p = 10; // assign 10 to count via p
Console.WriteLine("New value of count is " + *p);
}}
Using fixed
• The fixed keyword can be used only in an
unsafe context.
• The fixed modifier is often used when working
with pointers.
• It prevents a variable from being moved by
the garbage collector.
• This is needed when a pointer refers to a field
in a class object.
• Using pointers in C# require much more
attention then in C++. That is because of
garbage collector (g.c.) which can run memory
cleaning. During cleaning, g.c. can change
physical position of the objects. If g.c. changes
position of an object the pointer will point at
wrong place in memory. To avoid such
problems (connected with garbage collector)
C# contains 'fixed' keyword. It informs system
not to relocate an object by the garbage
collector.
•
•
•
•

using System;
class Test {
public int num;
public Test(int i) { num = i; }

•}
• class FixedCode {
• // Mark Main as unsafe.
• unsafe static void Main() {
Test o = new Test(19);
fixed (int* p = &o.num) {
Console.WriteLine("Initial value of o.num is " + *p);
*p = 10;
Console.WriteLine("New value of o.num is " + *p);
} }
• fixed prevents o from being moved. Because p
points to o.num , if o were moved, then p
would point to an invalid location.

More Related Content

PDF
Programs that work in c and not in c
PPT
Cinfo
PDF
escape sequences and substitution markers
PDF
csharp repitition structures
PPTX
Testing lecture after lec 4
PDF
PPT
Lecture 3 c++
PPT
Csc1100 lecture05 ch05
Programs that work in c and not in c
Cinfo
escape sequences and substitution markers
csharp repitition structures
Testing lecture after lec 4
Lecture 3 c++
Csc1100 lecture05 ch05

What's hot (20)

PPT
PPTX
Infix-Postfix expression conversion
PPTX
Infix postfixcoversion
PPTX
Evaluation of postfix expression
PPTX
How c program execute in c program
PDF
computer notes - Conversion from infix to postfix
PPT
Infix to Postfix Conversion Using Stack
PPTX
Infix to postfix
PPTX
Csc1100 lecture02 ch02-datatype_declaration
DOCX
Programming fundamentals
PPTX
Infix to postfix conversion
PDF
LLVM Overview
PDF
A simple program C# program
PPTX
3. user input and some basic problem
PPTX
C# 5.0
PPTX
2. introduction of a c program
PDF
Two C++ Tools: Compiler Explorer and Cpp Insights
PPTX
Conversion of Infix to Prefix and Postfix with Stack
PPS
C programming session 04
PDF
Chapter 2 - Structure of C++ Program
Infix-Postfix expression conversion
Infix postfixcoversion
Evaluation of postfix expression
How c program execute in c program
computer notes - Conversion from infix to postfix
Infix to Postfix Conversion Using Stack
Infix to postfix
Csc1100 lecture02 ch02-datatype_declaration
Programming fundamentals
Infix to postfix conversion
LLVM Overview
A simple program C# program
3. user input and some basic problem
C# 5.0
2. introduction of a c program
Two C++ Tools: Compiler Explorer and Cpp Insights
Conversion of Infix to Prefix and Postfix with Stack
C programming session 04
Chapter 2 - Structure of C++ Program
Ad

Viewers also liked (8)

PPTX
PPTX
Delegates and events
PPTX
C# Generics
PDF
C# Delegates, Events, Lambda
PPTX
C# Delegates
PPTX
Delegates and events
PPTX
Threading in C#
PDF
12 events and delegates
Delegates and events
C# Generics
C# Delegates, Events, Lambda
C# Delegates
Delegates and events
Threading in C#
12 events and delegates
Ad

Similar to Unsafe (20)

PPTX
PDF
C Sharp: Basic to Intermediate Part 01
PPT
79744777- FULL AND DETAILED LEVEL OF Pointers-in-c-Presentation.ppt
PPT
Csharp
PDF
Csharp_Chap03
PPTX
Notes(1).pptx
PPTX
Chapter3: fundamental programming
PDF
Csharp_Chap10
PDF
【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティス
PPTX
C++ Introduction brown bag
PDF
Pointer in c++ part3
PPT
Beware of Pointers
PPTX
CS4443 - Modern Programming Language - I Lecture (2)
PDF
【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティス(note付き)
PPT
C# programming language by dr. Yousef.ppt
PPTX
C# AND F#
PPTX
c# at f#
PPT
IntroductionToCSharppppppppppppppppppp.ppt
C Sharp: Basic to Intermediate Part 01
79744777- FULL AND DETAILED LEVEL OF Pointers-in-c-Presentation.ppt
Csharp
Csharp_Chap03
Notes(1).pptx
Chapter3: fundamental programming
Csharp_Chap10
【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティス
C++ Introduction brown bag
Pointer in c++ part3
Beware of Pointers
CS4443 - Modern Programming Language - I Lecture (2)
【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティス(note付き)
C# programming language by dr. Yousef.ppt
C# AND F#
c# at f#
IntroductionToCSharppppppppppppppppppp.ppt

More from abhay singh (15)

PPT
Iso 27001
PPT
Web service
PPTX
Threading
PPT
Preprocessor
PPT
Networking and socket
PPT
Namespace
PPT
Inheritance
PPT
Generic
PPT
PPT
Exception
PPT
Delegate
PPT
Constructor
PPT
Collection
PPT
PPT
Operator overloading
Iso 27001
Web service
Threading
Preprocessor
Networking and socket
Namespace
Inheritance
Generic
Exception
Delegate
Constructor
Collection
Operator overloading

Recently uploaded (20)

PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
01-Introduction-to-Information-Management.pdf
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
RMMM.pdf make it easy to upload and study
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Computing-Curriculum for Schools in Ghana
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Pharmacology of Heart Failure /Pharmacotherapy of CHF
STATICS OF THE RIGID BODIES Hibbelers.pdf
Chinmaya Tiranga quiz Grand Finale.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
01-Introduction-to-Information-Management.pdf
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
O5-L3 Freight Transport Ops (International) V1.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Microbial disease of the cardiovascular and lymphatic systems
Final Presentation General Medicine 03-08-2024.pptx
RMMM.pdf make it easy to upload and study
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Computing-Curriculum for Schools in Ghana
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Cell Structure & Organelles in detailed.
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Weekly quiz Compilation Jan -July 25.pdf
Anesthesia in Laparoscopic Surgery in India

Unsafe

  • 2. • Unsafe code often involves the use of pointers. • Unsafe code and pointers enable C# to be used to create applications that one might normally associate with C++: highperformance, systems code. • the inclusion of unsafe code and pointers gives C# capabilities that are lacking in Java.
  • 3. • Unsafe code is not code that is poorly written; it is code that does not execute under the full management of the common language runtime (CLR). • C# is normally used to create managed code. • It is possible, however, to write code that does not execute under the full control of the CLR. This unmanaged code is not subject to the same controls and constraints as managed code, so it is called “unsafe”. • it is not possible to verify that it won’t perform some type of harmful action.
  • 4. • Because a pointer can point anywhere in memory, it is possible to misuse a pointer. • It is also easy to introduce a coding error when using pointers. This is why C# does not support pointers when creating managed code. • C# does allow you to create and use pointers. However, all pointer operations must be marked as unsafe since they execute outside the managed context.
  • 5. Declaring a Pointer • Pointer variables must be declared as such. type * var-name ; • type is the pointer’s referent type. • var-name is the name of the pointer variable. • example. To declare ip to be a pointer to an int, use this declaration: int* ip;
  • 6. • If you come from a C/C++ background, then you need to be aware of an important difference between the way C# and C/C++ declare pointers. • When you declare a pointer type in C/C++, the * is not distributive over a list of variables in a declaration. • Thus, in C/C++, this statement int* p, q;
  • 7. • in C#, the * is distributive and the declaration int* p, q; • creates two pointer variables. • Thus, in C# it is the same as these two declarations: int* p; int* q;
  • 8. • Two operators are used with pointers: * and &. • The & is a unary operator that returns the memory address of its operand. • int* ip; • int num = 10; • ip = # • puts into ip the memory address of the variable num. • ip does not contain the value 10.
  • 9. • The second operator is *, and it is the complement of &. • it refers to the value of the variable pointed to by a pointer. • ip = # • int val = *ip; • will place into val the value 10, which is the value of num, which is pointed to by ip .
  • 10. unsafe • Any code that uses pointers must be marked as unsafe by using the unsafe keyword. • You can mark types (such as classes and structures), members (such as methods and operators), or individual blocks of code as unsafe. • using System; • class UnsafeCode {
  • 11. // Mark Main as unsafe. unsafe static void Main() { int count = 99; int* p; // create an int pointer p = &count; // put address of count into p Console.WriteLine("Initial value of count is " +*p); *p = 10; // assign 10 to count via p Console.WriteLine("New value of count is " + *p); }}
  • 12. Using fixed • The fixed keyword can be used only in an unsafe context. • The fixed modifier is often used when working with pointers. • It prevents a variable from being moved by the garbage collector. • This is needed when a pointer refers to a field in a class object.
  • 13. • Using pointers in C# require much more attention then in C++. That is because of garbage collector (g.c.) which can run memory cleaning. During cleaning, g.c. can change physical position of the objects. If g.c. changes position of an object the pointer will point at wrong place in memory. To avoid such problems (connected with garbage collector) C# contains 'fixed' keyword. It informs system not to relocate an object by the garbage collector.
  • 14. • • • • using System; class Test { public int num; public Test(int i) { num = i; } •} • class FixedCode { • // Mark Main as unsafe. • unsafe static void Main() {
  • 15. Test o = new Test(19); fixed (int* p = &o.num) { Console.WriteLine("Initial value of o.num is " + *p); *p = 10; Console.WriteLine("New value of o.num is " + *p); } } • fixed prevents o from being moved. Because p points to o.num , if o were moved, then p would point to an invalid location.