Reputation: 2439
I have one method which is in child class and I want to fetch that in Parent with the help of this.
public class Class1
{
private class Class2
{
public void Add(int a, int b) // Method in Class 2
{
this.Add(a, b);
}
}
public Class1() // constructor of Class 1
{
// Get this Add method by This.Add ??
// Not able to fetch the Add method here.
}
}
Upvotes: 2
Views: 491
Reputation: 5506
You need to create instance for Class2
public class Class1
{
private class Class2
{
public Class2() // constructor of Class2
{
}
public void Add(int a, int b) // Method in Class2
{
this.Add(a, b);
}
}
public Class1() // constructor of Class1
{
Class2 cs2 = new Class2();
cs2.Add(4,5);
}
}
Upvotes: 0
Reputation: 5921
public class Class1
{
private class Class2
{
public void Add(int a, int b) // Method in Class 2
{
this.Add(a, b);
}
}
public Class1() // constructor of Class 1
{
Class2 newclass2 = new Class2();
newclass2.Add(1, 2);
// Get this Add method by This.Add ??
// Not able to fetch the Add method here.
}
}
Upvotes: 0
Reputation: 11597
you have declared the method but it is in class2
. that means you need to create an instance of class2
in order to use the method
public class Class1
{
private class Class2
{
public void Add(int a, int b) // Method in Class 2
{
this.Add(a, b);
}
}
public Class1() // constructor of Class 1
{
class2 cs = new class2();
cs.Add(4,5);
}
}
Upvotes: 2
Reputation: 166566
You would either have to create an instance of Class2 in the constructor of Class1 and use an instance method, or change the method Add to static in Class2
Static version
Something like
public class Class1
{
private class Class2
{
public static void Add(int a, int b)
{
}
}
public Class1()
{
Class2.Add(1,2);
}
}
Instance version
Something like
public class Class1
{
private class Class2
{
public void Add(int a, int b)
{
}
}
public Class1()
{
new Class2().Add(1,2);
}
}
Maybe have a look at static (C# Reference)
Upvotes: 1