Create partial (partial) method in C#

Asked

Viewed 154 times

1

You can create a method similar to a class that is partial?

For example:

Has the method $InitializeComponent() which is of the class of a form.

I want to increment this function without touching the original (create a proxy). There’s a way I can do that?

What I tried and not your right was:

partial class form1
{
    ...
    private void InitializeComponent()
    {
        ...
    }
    ...
}

partial class form1 : Form
{
     ...
     partial void InitializeComponent()
     {
           ...
     }
}

1 answer

3


Yes it is possible, it really is called partial method. But maybe it doesn’t do what you want. You can’t write part of the method code in one place and part in another. What you can do is declare the method in one part and define its code in another part. As in C/C++.

I think it really is unnecessary to do this but if you really want to, if you think you have a real reason to do it, what you can do is create a main method and call another helper who is in the other part. Partial method was created to facilitate use with code generators, to generate the statement and ensure that the programmer will create the implementation in another file.

Method has algorithm, it is different from a class that is a data structure. In the data structure the position where each element is is not very important. The compiler can manage well with this.

In an algorithm this part of the code will enter where? The compiler has no way of knowing which goes first, or worse, if it is to enter the middle. Only the programmer can tell how this will be done. Then just make a call to another method in the appropriate location.

If you really want to do a proxy, do a proxy proxy.

I still think you’re trying to make a gambit that is either not possible or will not go in good.

Archiv11

partial class form1 {
    ...
    private void InitializeComponent() {
        ...
        InitializeComponentAux();
    }
    ...
}

Arquivo2

partial class form1 : Form {
     ...
     partial void InitializeComponentAux() {
           ...
     }
}

With the partial method official could only do this:

Archiv11

partial class form1 {
    ...
    private void InitializeComponent();
    ...
}

Arquivo2

partial class form1 : Form {
     ...
     partial void InitializeComponent() {
           ...
     }
}

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.