use of assigning the object impelementing a interface to an interface [modified]
-
Hi guys , I came across a piece of code similar to the below one. public partial class Form1 : Form { private void Form1_Load(object sender, EventArgs e) { ad test = new ad(); Ia id5 = test.testobj(); id5.display() } } public interface Ia { void display(); } public class b : Ia { public void display() { MessageBox.Show("do it man"); } } public class ad { public Ia testobj() { b gh = new b(); return gh; } } My question is why should we typecast object gh to interface Ia in testobj() function as the interface object when we can directly use the object of class b to call display function. Thans in advance, sishya -- modified at 5:54 Friday 27th April, 2007
-
Hi guys , I came across a piece of code similar to the below one. public partial class Form1 : Form { private void Form1_Load(object sender, EventArgs e) { ad test = new ad(); Ia id5 = test.testobj(); id5.display() } } public interface Ia { void display(); } public class b : Ia { public void display() { MessageBox.Show("do it man"); } } public class ad { public Ia testobj() { b gh = new b(); return gh; } } My question is why should we typecast object gh to interface Ia in testobj() function as the interface object when we can directly use the object of class b to call display function. Thans in advance, sishya -- modified at 5:54 Friday 27th April, 2007
Because the point of an interface is that lots of objects can impliment it, and, despite their differences, they can exist as an instance of that interface via the same collection, or variable.
Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )
-
Hi guys , I came across a piece of code similar to the below one. public partial class Form1 : Form { private void Form1_Load(object sender, EventArgs e) { ad test = new ad(); Ia id5 = test.testobj(); id5.display() } } public interface Ia { void display(); } public class b : Ia { public void display() { MessageBox.Show("do it man"); } } public class ad { public Ia testobj() { b gh = new b(); return gh; } } My question is why should we typecast object gh to interface Ia in testobj() function as the interface object when we can directly use the object of class b to call display function. Thans in advance, sishya -- modified at 5:54 Friday 27th April, 2007
In this example, it is not necessary since the example doesn't do anything much. The reason to do so would be if other classes implemented the interface and you want to call display() for a collection of different classes using a common variable of type Ia. GregD (My Blog on software development)