Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the class NativeMethods handled specially in .NET?

https://msdn.microsoft.com/en-us/library/ms182161.aspx

Are the three classes described on this paged handled specially in the .NET Framework? (NativeMethods, SafeNativeMethods and UnsafeNativeMethods)

The reason I'm asking is I'm wondering if it is alright to create categories of NativeMethods classes. For example:

ComNativeMethods
User32NativeMethods
OleStorageNativeMethods
like image 688
Bryan Avatar asked Sep 18 '09 15:09

Bryan


4 Answers

It's a convention, not a requirement. If you reflect into the CLR and take a look at code in there, you'll often see P/Invoke code inside a NativeMethods class. I believe that FxCop will recommend putting your P/Invoke code in a class like this if it encounters it.

like image 196
Pete OHanlon Avatar answered Sep 17 '22 23:09

Pete OHanlon


It's just a convention that says you should place p/invoke methods in classes named *NativeMethods, but there is no technical constraint to prevent you from doing it your own way...

like image 31
Thomas Levesque Avatar answered Sep 18 '22 23:09

Thomas Levesque


You can name your classes that way, but you will continue to get the code analysis warning CA1060. This warning indicates you are not following the convention. So to prevent this warning, you need to follow the convention when naming classes that have P/Invoke methods. If you want to categorize your P/Invoke methods, you can use namespaces. For example:

  • MyProject.Com.NativeMethods
  • MyProject.User32.NativeMethods
  • MyProject.OleStorage.NativeMethods
like image 21
Ed Greaves Avatar answered Sep 18 '22 23:09

Ed Greaves


They aren't handled specially by the CLR. It's simply recommended practice to have your P/Invokes inside a class named NativeMethods, SafeNativeMethods, or UnsafeNativeMethods.

You'll see this recommendation come into play if you run FxCop on your assemblies.

like image 29
Judah Gabriel Himango Avatar answered Sep 19 '22 23:09

Judah Gabriel Himango