A Partial method is a special method that exist with in a partial class or struct. One part of the partial class or struct have only partial method declaration means signature and another part of the same partial class or struct may have implementation for that partial method. If the implementation is not provided for declared partial method, the method and all calls to that partial methods will be removed at compile time. For more about Partial Class, Interface or Struct refer the article Partial Class, Interface or Struct in C Sharp with example
Why partial methods required ?
Partial methods are particularly helpful for customizing auto generated code by the tool. Whenever the tool generate the code then tool may decalare some partial method and implementation of these methods is decided by the developers.
If you are using entity framework for making DAL then you have seen that the Visual Studio make a partial method OnContextCreated() as shown below. Now the implementation of it depends on you whether you want to use it or not.
- public partial class DALEntities : ObjectContext
- {
- #region Constructors
- // Constructors for DALentities
- #endregion
- #region Partial Methods
- partial void OnContextCreated();
- #endregion
- }
- // This part can be put in the separate file
- public partial class DALEntities : ObjectContext
- {
- partial void OnContextCreated()
- {
- // put method implementation code
- Debug.WriteLine("OnContextCreated partial method");
- }
- }
Key points about partial method
- Partial methods can be declared or defined with in the partial class or struct.
- Partial methods are implicitly private and declarations must have partial keyword.
- Partial methods must return void.
- Partial methods implementation is optional.
- Partial methods can be static and unsafe and generic.
- Partial methods can have ref parameters but not out parameters since these can't return value.
- You can also make a delegate to a partial method that has been defined and implemented. If the partial method is only defined, you can not.
- The signatures of partial method will be same in both parts of the partial class or struct.
- partial class Example
- {
- partial void ExampleMethod(string s);
- }
- // This part can be put in the separate file
- partial class Example { //Implement the method
- partial void ExampleMethod(String s)
- {
- Console.WriteLine("Your string: {0}", s);
- }
- }
No comments:
Post a Comment