0

I have question about c# partial method. How to use(call from main) partial methods if they are private by default?

using System;
namespace SecondProject
{
    internal class Program
    {
        partial class Person
        {   
            partial void foo();
        }

        partial class Person
        {
            partial void foo() => Console.WriteLine("foo");
        }

        static void Main(string[] args)
        {
            Person person = new Person();
            person.foo(); // person.foo() is inaccessible due to its protection level
        }
    }
}
Gevv
  • 25
  • 7
  • 3
    You don't. You should not try to call private members of a type outside of that type. It is private for a reason. If that was not the intention then make it `public` (or `internal`). – Igor Aug 19 '22 at 16:25
  • @Igor But I don't understand how to use implementation of partial method if it is private? – Gevv Aug 19 '22 at 16:29
  • 1
    Partial methods are for code generation scenarios, where generated code calls the method, but if there's no implementation provided by the user-managed file, the call is removed entirely. Unless you're doing code generation, partial methods are not a good choice.. (The visibility restrictions were relaxed in a recent version of C#, but that also means that implementation by a *source generator* is required.) – madreflection Aug 19 '22 at 16:34

1 Answers1

0

Partial classes and methods are basically there to spread your code over multiple files, for example because one part of the code is generated (and changes to it will be overwritten).

It has nothing to do with accessibility (private/protected/internal/public), and after compilation there's no difference between a partial or non-partial method.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272