NativeMethods Class  
Author Message
AndyJ_PS





PostPosted: Visual C# General, NativeMethods Class Top

Every now and then I uncover a little reference or information on NativeMethod classes. As far as I can see they are for putting pInvokes into.

Can anyone shed any light on why this is necessary, if I should include constants and structs in that class as well and well any information on them.


Visual C#14  
 
 
Brendan Grant





PostPosted: Visual C# General, NativeMethods Class Top

When it comes to Pinvokes there are few requirements on where they can be declared or their visibility however object oriented design principals dictate amongst other things, encapsulation and abstraction of specific implementation details.

One historical way to accomplish this has been to round up all of the various Pinvokes used by an application, library or other large block of code and declare them in an internal sealed class that is often named NativeMethods so that callers within the app/lib can access them, but their existence and specifics of are hidden from anyone who codes against the app/lib and allows access only through those classes/methods/properties that you have exposed.

Note though that nothing says you have to put most/all of your Pinvokes in a NativeMethods class... it is considered by many to be the proper thing to do as it increases code readability and maintainability.

When it comes to defining constants in your own NativeMethods class, that’s up to you. Personally when I use one I put anything and everything directly related to the Pinvokes in there, items like the structs, enums and constants.



 
 
AndyJ_PS





PostPosted: Visual C# General, NativeMethods Class Top

Thats a great overview, many thanks :)