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
        }
    }
}
3
  • 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). Commented Aug 19, 2022 at 16:25
  • @Igor But I don't understand how to use implementation of partial method if it is private? Commented Aug 19, 2022 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.) Commented Aug 19, 2022 at 16:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.