Skip to content

C# structure

Neo

Asked May 13, 2008, 5:55 PM EDT2 answers
Share
LinkedInX

Hi,

I just gone through following link

http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=120

read following code lines. However following code is fine I guess because function MyMethod not initialise any variable. Although you declare  MyInterface obj= new MyStruct();  still it will work. Please comment.

 

C#
interface MyInterface
    {
         void MyMethod();
    }
    struct MyStruct : MyInterface
    {
        public  void MyMethod()
        {
            Console.WriteLine("Struct Method from MyStruct");
            Console.ReadLine();

        } 

    } // end of structure
    class Class1
    {
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main(string[] args)
        {
             MyInterface obj= new MyStruct();
                 
            obj.MyMethod(); // this is error
    
        }
    } // end of main class

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    When you create an instance of MyStruct and depose it as an instance of MyInterface, your simply exposing the members of MyInterface in the object you create, not MyStruct. I call it downcasting, because your casting a decendant class to a baser class.

    However, obj.MyMethod() should work because its defined in the MyInterface interface. I just tested it and it worked in Visual Studio 2005.

    I think this example shows another form of polymorphism if Im right... or may its composition, I cant remember :( Either way its an object oriented sample. Look at it this way:

    Since MyStruct implements the interface MyInterface, it -IS- a MyInterface. Therefore it can be cast to type MyInterface :)
    0
  • 0

    yeah it's polymorphism only; But I am jst wondered the one who posted this article made mistake he/she said error in code which is not true.

    0