Pergunta

i was recently digging on new partial methods in c#3.0, i understood the use of partial class, that it could be chunked into multiple file one contain the definition and other declaration, but i wanted to know,i created a partial class like below:

in class1.cs
partial class A
{
   partial void Method();
}
in class2.cs
partial class A
{
  partial void Method()
  {
    Console.WriteLine("Hello World");
  }
}
now in class3.cs
class MainClass
{
  static void Main()
  {
    A obj = new A();
    obj.Method(); //Here i cannot call the "Method" method.
  }
}

then whats the use of creating partial method, i read on MSDN that, at runtime, compiler compiles the class into one, in that case compiler should be getting the "Method" method implementation also, then why it dont allow me to call the "Method" method in the main method, can anyone correct me if i am wrong, and tell me why i am unable to call this partial method in main.

Foi útil?

Solução

From MSDN

No access modifiers or attributes are allowed. Partial methods are implicitly private.

It's a private method, so you can't call it from main.

Outras dicas

You can call a partial method inside the constructor where the method is defined.

For example

    public partial class classA
    {
      partial void mymethod();
    }
    public partial class classA
    {
      partial void mymethod()
      {
         Console.WriteLine("Invoking partial method");
      }
      public ClassA()
      {
        mymethod();
      }


    }
public class MainClass
{
   static void Main()
   {
      ClassA ca=new ClassA();
   }
}

That's it..now execute your code and see the result..

  • OutPut

Invoking partial method

Yes, we can't call it from Main(). Problem is not Partial method problem is method without specifier in a class is Private and private method can be called inside the class only.

Try creating a new public method in Partial class:

partial class A
{
  partial void Method();
}

partial class A
{
  partial void Method()
  {
    Console.WriteLine("Hello World");
  }
  public void Study()
  {
    Console.WriteLine("I am studying");
    Method();
  }
}

class MainClass
{
  static void Main()
  {
    A obj = new A();
    obj.Study(); 
  }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top