views:

72

answers:

4

why i generate instance outside of class. i give inheritance snifC to sinifD i need to create instance sinifC sinifc= new sinifC() in SinifD out side of constructor?

  public  class sinifC
    {
       public  void method3()
        {
            Console.WriteLine("Deneme3");
        }
    }

   public class sinifD : sinifC
    {
        void method4()
        {
            Console.WriteLine("Deneme4");
        }

        public sinifD()
        {
            sinifC sinifc = new sinifC();
            sinifc.method3();
        }
    }

i want to make it below:


    public  class sinifC
    {
       public  void method3()
        {
            Console.WriteLine("Deneme3");
        }
    }

   public class sinifD : sinifC
    {
        void method4()
        {
            Console.WriteLine("Deneme4");
        }


            sinifC sinifc = new sinifC();
            sinifc.method3();

    }

Error: Invalid token '(' in class, struct, or interface member declaration

+3  A: 

doesn't

        sinifC sinifc = new sinifC();
        sinifc.method3();

need to be inside a method?

You seem to want to create an instance of an object and call its method inside the body of the class, but you need to have it happen inside a method.

DaveDev
More specifically, you can create a new object in its declaration, but not call `method3()` on it.
R. Bemrose
thanks, I just realised what I wrote "create an instance of a method".. tsk tsk! :-)
DaveDev
+2  A: 

You don't have to write the code in the constructor, but you do have to write the code in some method. You're currently just writing the code anywhere in your class. If you don't want to have to create an instance of your D class to do this you could create a static method in your D class that creates the instance of the C class (you could even have a static constructor).

ho1
+1  A: 

The only valid instructions in the body of a class are declarations (optionally including initialization for fields). A method call is not a valid instruction here, it has to be inside a method

Thomas Levesque
+1  A: 

You do not need to create an instance of sinifC - you are using inheritace by extending it.

class Program
{
    static void Main(string[] args)
    {
        sinifD s = new sinifD();

        // call method3 on sinfiD
        s.method3();
    }
}

public  class sinifC
{
   public  void method3()
    {
        Console.WriteLine("Deneme3");
    }
}

public class sinifD : sinifC
{
    // sinifD inheritrs mehtod3 from sinifD

    // method 4 is protected, so only classes in the class hierachy see that method
    void method4()
    {
        Console.WriteLine("Deneme4");
    }
}
spookycoder