SlideShare uma empresa Scribd logo
1 de 15
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.

Mais conteúdo relacionado

Mais procurados

Infix-Postfix expression conversion
Infix-Postfix expression conversionInfix-Postfix expression conversion
Infix-Postfix expression conversionRashmiranja625
 
Infix postfixcoversion
Infix postfixcoversionInfix postfixcoversion
Infix postfixcoversionPdr Patnaik
 
Evaluation of postfix expression
Evaluation of postfix expressionEvaluation of postfix expression
Evaluation of postfix expressionAkhil Ahuja
 
How c program execute in c program
How c program execute in c program How c program execute in c program
How c program execute in c program Rumman Ansari
 
computer notes - Conversion from infix to postfix
computer notes - Conversion from infix to postfixcomputer notes - Conversion from infix to postfix
computer notes - Conversion from infix to postfixecomputernotes
 
Infix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using StackInfix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using StackSoumen Santra
 
Csc1100 lecture02 ch02-datatype_declaration
Csc1100 lecture02 ch02-datatype_declarationCsc1100 lecture02 ch02-datatype_declaration
Csc1100 lecture02 ch02-datatype_declarationIIUM
 
Programming fundamentals
Programming fundamentalsProgramming fundamentals
Programming fundamentalsZaibi Gondal
 
A simple program C# program
A simple program C# programA simple program C# program
A simple program C# programMicheal Ogundero
 
3. user input and some basic problem
3. user input and some basic problem3. user input and some basic problem
3. user input and some basic problemAlamgir Hossain
 
2. introduction of a c program
2. introduction of a c program2. introduction of a c program
2. introduction of a c programAlamgir Hossain
 
Two C++ Tools: Compiler Explorer and Cpp Insights
Two C++ Tools: Compiler Explorer and Cpp InsightsTwo C++ Tools: Compiler Explorer and Cpp Insights
Two C++ Tools: Compiler Explorer and Cpp InsightsAlison Chaiken
 
Conversion of Infix to Prefix and Postfix with Stack
Conversion of Infix to Prefix and Postfix with StackConversion of Infix to Prefix and Postfix with Stack
Conversion of Infix to Prefix and Postfix with Stacksahil kumar
 
C programming session 04
C programming session 04C programming session 04
C programming session 04AjayBahoriya
 
Chapter 2 - Structure of C++ Program
Chapter 2 - Structure of C++ ProgramChapter 2 - Structure of C++ Program
Chapter 2 - Structure of C++ ProgramDeepak Singh
 

Mais procurados (20)

Lab 1
Lab 1Lab 1
Lab 1
 
Infix-Postfix expression conversion
Infix-Postfix expression conversionInfix-Postfix expression conversion
Infix-Postfix expression conversion
 
Infix postfixcoversion
Infix postfixcoversionInfix postfixcoversion
Infix postfixcoversion
 
Evaluation of postfix expression
Evaluation of postfix expressionEvaluation of postfix expression
Evaluation of postfix expression
 
How c program execute in c program
How c program execute in c program How c program execute in c program
How c program execute in c program
 
computer notes - Conversion from infix to postfix
computer notes - Conversion from infix to postfixcomputer notes - Conversion from infix to postfix
computer notes - Conversion from infix to postfix
 
Infix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using StackInfix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using Stack
 
Infix to postfix
Infix to postfixInfix to postfix
Infix to postfix
 
Csc1100 lecture02 ch02-datatype_declaration
Csc1100 lecture02 ch02-datatype_declarationCsc1100 lecture02 ch02-datatype_declaration
Csc1100 lecture02 ch02-datatype_declaration
 
Programming fundamentals
Programming fundamentalsProgramming fundamentals
Programming fundamentals
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
 
LLVM Overview
LLVM OverviewLLVM Overview
LLVM Overview
 
A simple program C# program
A simple program C# programA simple program C# program
A simple program C# program
 
3. user input and some basic problem
3. user input and some basic problem3. user input and some basic problem
3. user input and some basic problem
 
C# 5.0
C# 5.0C# 5.0
C# 5.0
 
2. introduction of a c program
2. introduction of a c program2. introduction of a c program
2. introduction of a c program
 
Two C++ Tools: Compiler Explorer and Cpp Insights
Two C++ Tools: Compiler Explorer and Cpp InsightsTwo C++ Tools: Compiler Explorer and Cpp Insights
Two C++ Tools: Compiler Explorer and Cpp Insights
 
Conversion of Infix to Prefix and Postfix with Stack
Conversion of Infix to Prefix and Postfix with StackConversion of Infix to Prefix and Postfix with Stack
Conversion of Infix to Prefix and Postfix with Stack
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 
Chapter 2 - Structure of C++ Program
Chapter 2 - Structure of C++ ProgramChapter 2 - Structure of C++ Program
Chapter 2 - Structure of C++ Program
 

Destaque (8)

Generics C#
Generics C#Generics C#
Generics C#
 
Delegates and events
Delegates and eventsDelegates and events
Delegates and events
 
C# Generics
C# GenericsC# Generics
C# Generics
 
C# Delegates, Events, Lambda
C# Delegates, Events, LambdaC# Delegates, Events, Lambda
C# Delegates, Events, Lambda
 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
 
Delegates and events
Delegates and events   Delegates and events
Delegates and events
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
 
12 events and delegates
12   events and delegates12   events and delegates
12 events and delegates
 

Semelhante a Unsafe

POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit DubeyMCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubeykiranrajat
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5thConnex
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)Shoaib Ghachi
 
Programming using c++ tool
Programming using c++ toolProgramming using c++ tool
Programming using c++ toolAbdullah Jan
 
The Ring programming language version 1.5.4 book - Part 82 of 185
The Ring programming language version 1.5.4 book - Part 82 of 185The Ring programming language version 1.5.4 book - Part 82 of 185
The Ring programming language version 1.5.4 book - Part 82 of 185Mahmoud Samir Fayed
 
Lap trinh C co ban va nang cao
Lap trinh C co ban va nang caoLap trinh C co ban va nang cao
Lap trinh C co ban va nang caoVietJackTeam
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Ali Aminian
 

Semelhante a Unsafe (20)

#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit DubeyMCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
MCA 101-Programming in C with Data Structure UNIT I by Prof. Rohit Dubey
 
C language
C languageC language
C language
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Lecture1
Lecture1Lecture1
Lecture1
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Programming using c++ tool
Programming using c++ toolProgramming using c++ tool
Programming using c++ tool
 
Pointers
PointersPointers
Pointers
 
The Ring programming language version 1.5.4 book - Part 82 of 185
The Ring programming language version 1.5.4 book - Part 82 of 185The Ring programming language version 1.5.4 book - Part 82 of 185
The Ring programming language version 1.5.4 book - Part 82 of 185
 
Embedded _c_
Embedded  _c_Embedded  _c_
Embedded _c_
 
Lap trinh C co ban va nang cao
Lap trinh C co ban va nang caoLap trinh C co ban va nang cao
Lap trinh C co ban va nang cao
 
Inline function
Inline functionInline function
Inline function
 
Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1Learning C++ - Introduction to c++ programming 1
Learning C++ - Introduction to c++ programming 1
 
CPP03 - Repetition
CPP03 - RepetitionCPP03 - Repetition
CPP03 - Repetition
 

Mais de abhay singh (15)

Iso 27001
Iso 27001Iso 27001
Iso 27001
 
Web service
Web serviceWeb service
Web service
 
Threading
ThreadingThreading
Threading
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
 
Networking and socket
Networking and socketNetworking and socket
Networking and socket
 
Namespace
NamespaceNamespace
Namespace
 
Inheritance
InheritanceInheritance
Inheritance
 
Generic
GenericGeneric
Generic
 
Gdi
GdiGdi
Gdi
 
Exception
ExceptionException
Exception
 
Delegate
DelegateDelegate
Delegate
 
Constructor
ConstructorConstructor
Constructor
 
Collection
CollectionCollection
Collection
 
Ado
AdoAdo
Ado
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 

Último

SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code ExamplesPeter Brusilovsky
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMELOISARIVERA8
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppCeline George
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFVivekanand Anglo Vedic Academy
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...EduSkills OECD
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................MirzaAbrarBaig5
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...Nguyen Thanh Tu Collection
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhleson0603
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...EADTU
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...Nguyen Thanh Tu Collection
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024Borja Sotomayor
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...Nguyen Thanh Tu Collection
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi RajagopalEADTU
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital ManagementMBA Assignment Experts
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxMohamed Rizk Khodair
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesAmanpreetKaur157993
 

Último (20)

SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptx
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 

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.