Reputation: 5884
Is there any difference between using keyword unsafe
before method or before block of code?
Will it be wrong if I use it before method when i have only few lines of unsafe code and hundreds of safe code?
Upvotes: 3
Views: 3392
Reputation: 17327
This is a subjective answer but I'd use unsafe
on the method level, like this:
private unsafe int MyFunc ( ... )
{
...
}
When you use unsafe
inside the body of the function, it's hidden away and it's hard to find, while something like this should be very apparent. Everybody will read the function declaration but not everyone will go into the function body, unless they need to.
Having unsafe
in the declaration makes it stand out more.
Upvotes: 6
Reputation: 43523
To answer your first question: See C# 4.0 spec chapter: 18.1
The unsafe features of C# are available only in unsafe contexts. An unsafe context is introduced by including an unsafe modifier in the declaration of a type or member, or by employing an unsafe-statement:
• A declaration of a class, struct, interface, or delegate may include an unsafe modifier, in which case the entire textual extent of that type declaration (including the body of the class, struct, or interface) is considered an unsafe context.
• A declaration of a field, method, property, event, indexer, operator, instance constructor, destructor, or static constructor may include an unsafe modifier, in which case the entire textual extent of that member declaration is considered an unsafe context.
• An unsafe-statement enables the use of an unsafe context within a block. The entire textual extent of the associated block is considered an unsafe context.
The second one: Of course it's NOT WRONG according to the conclusion of the first question. But I'd prefer wrap a few lines of unsafe codes with unsafe
statement, because it's more clearer and easy to find.
Upvotes: 1
Reputation: 787
Unsafe code allows you to address the memory directly and as such it can have pros and cons. I have done some reading in regards to your question through this article: http://www.codeproject.com/Articles/2363/Unsafe-programming-in-C and I hope it might lead you in the right direction. Good luck!
Upvotes: 0