Search code examples
c#unsafe

Keyword "unsafe" - before method or block of code?


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?


Solution

  • 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.