locked
Simple C# Question regarding Classes and Inheritance. RRS feed

  • Question

  • Hi Guys,  These are probably very simple question for a  lot of you.  Could I ask you be really clear and gentle with me, maybe step by step if you have time :-)   OK here it goes......... 

    1)  Say we are using the xmlreader class.  Now my understanding is that you cannot create an object of this class but can only inherit  by doing this.....

                              xmlreader  reader;

    Ok so now ''reader'' has all the methods, fields and parameters of xmlreader (as it would outline in object browser in visual studio)

    now in order to link  the path or file to the xml document, I have to assign it to ''reader''  by using the create method of xmlreader this.........

                              reader =  xmlreader.create(''c:\\test.xml")

    now usually when you assign 'something' to 'something' you give it a variable.  From my logic  ''reader'' is now a copy of xmlreader class so what property or field inside ''reader'' holds  whatever '' xmlreader.create(''c:\\test.xml") '' did??

     for example if we go to read ''reader'' by using......

                                                                          if (reader.read())

    How does the method 'read' know where to look in reader to find ''c:\\test.xml"  ??



    2)  


    Why do we sometimes use the keyword 'new' and othertimes not for example if we pretend that the above xmlreader we could make an object  then why are we not  doing this

                                                xmlreader  reader = new xml reader();  (it must have a constructor surely ? )

    why are we only   dong this by....

                                                 xmlreader reader;

    I think if I can understand this - I will be able to understand alot more principles.

    Thanks everyone.




                             reader  = xml




    Thursday, March 11, 2010 8:55 PM

Answers

  • Your typing has me confused, as it is all over the place.
    You seem to have your signals crossed on a number of fundamentals.
    Does the following code make any sense to you?


        public class SomeClass
        {
            XmlReader reader;  // declare variable of type XmlReader
            
            public SomeClass()  // this is a constructor
            {
            }
            public void TestMethod()
            {
                reader = XmlReader.Create("myfile.xml");  // create reader instance
    
            }
        }
        public class AnotherClass
        {
            SomeClass obj;  // declare variable of type SomeClass
    
            public AnotherClass()  // this is a constructor
            {
                obj = new SomeClass();  // create instance
                obj.TestMethod();  // execute test method
            }
        }



    I used the Code Formatting Tool to post my code.
    It is the icon that looks like this ' </> "

    Rudy  =8^D

    Mark the best replies as answers. "Fooling computers since 1971."
    • Marked as answer by liurong luo Tuesday, March 16, 2010 10:47 AM
    Thursday, March 11, 2010 9:09 PM
  • 1)

      1.1. "XmlReader reader;" is not inheriting. it's declaring an object from XmlReader class named reader and by this declaration it's null
               currently because you don't instant it by new keyword.
      1.2. Yes, it has all methods/properties but they are unusable because it's null currently.

      1.3. Create method is a static method which help you create an instance from XmlReader.

      1.4. It know it's file because the file name is stored in it some where.

    2)

    Yes, some classes doesn't have direct constructor and you should create instance from them by some static methods.


    My Blog - MSDN Complement by providing Visual C# Walkthroughs and Sample Codes - Founded In February 24, 2010
    • Marked as answer by liurong luo Tuesday, March 16, 2010 10:47 AM
    Thursday, March 11, 2010 9:11 PM
  • Hi,

    Abstract Class:
                 C# allows both classes and functions to be declared as abstract.An abstract class cannot be instantiated where as an abstract function doesnt have implementation and must be overriden in any non abstract derived class.

    XmlReader is an abstract class. That means it cant be instantiated.

    When you say "XmlReader reader;" it doesnt actually create any object. Its just a declaration.

    Static Modifier:
               The member doesnt operate on specific instance of the class.

    XmlReader.Create is a static method.

    So you are using "XmlReader reader = XmlReader.Create("test.xml");" to create an object and use it.

    Coming to reader.Read(),it is a method which keeps reading the xml file node by node.

    To the above question you asked:

    1) It doesnt work. They have to be same type.
    2)Your source code is compiled to byte code(CIL code) by C# compiler and then it is converted to Native code by CLR.

    To run on a machine,it has to be in Native code. So your source code is converted to byte code by the compiler and that code is converted to Native code by the CLR on the machine to run it.



     






    • Marked as answer by liurong luo Tuesday, March 16, 2010 10:47 AM
    Friday, March 12, 2010 2:06 PM
  • Your last question first.  You must use the same class or type , is the short answer.  Let's postpone the longer answer for now.

    1)  XmlReader is one many types defined within the FCL, Framework Class Library.

    2)  Yes, we are defining a variable named reader of type XmlReader.  Space is created somewhere for this variable name, but the actual variable has not yet been defined and assigned to the variable.  This reference type variable is null at this point.  Instantiating the variable means allocating memory space and filling it with an instance object, an object graph of the type.

    3)  You are using type Int32 to declare your variable myAge.  Substitute the "Int32" in the place of "int" and you will get the same result.  But, note how the two words are displayed in different colors.  Int32 is displayed as cyan because it is a type.  The word "int" is displayed as blue because it is a C# keyword.  A keyword that currently uses the type Int32 to define an Integer.  50 years from now, the keyword might define Int256.

    4)  Yes, XmlReader is a Reference Type, and Int32 is a Value Type.

    5)  In a sense, you might say that XmlReader passes on its' class members to the reader variable.  But, view can lead to misconceptions because not all class members get passed on to an instance object.  The variable actually "Is A" XmlReader instance, an instance object of type XmlReader.

         The method call to CreateReader creates a reader object and returns it to the caller, which means the right side of the equals sign.  It is a special method that is used to construct the highly complex XmlReader object instance.  Normally, we would simply call a constructor much like the ones that I identified in my snippet.  It would seem that XmlReader must require many parameters and probably many steps to fully construct.  They created what is known as a Factory Method to create object instances for us, so that we don't mess it up and re-write our hard drives.

         The XmlReader, like most of the other XXXX Reader types, reads the file sequentially from start to finish.  It does not have random access, and it cannot back up.  It can only move forward.  The Read method directs the XmlReader instance to read the next piece of data out of the file.  Since it is an XmlReader it will read the next XML element.  If it were a TextReader, it would read the next character.

    6)  I think you might be stocked with enough info in this reply to answer this question for yourself. 

    Mark the best replies as answers. "Fooling computers since 1971."
    • Marked as answer by liurong luo Tuesday, March 16, 2010 10:47 AM
    Friday, March 12, 2010 2:21 PM

All replies

  • Your typing has me confused, as it is all over the place.
    You seem to have your signals crossed on a number of fundamentals.
    Does the following code make any sense to you?


        public class SomeClass
        {
            XmlReader reader;  // declare variable of type XmlReader
            
            public SomeClass()  // this is a constructor
            {
            }
            public void TestMethod()
            {
                reader = XmlReader.Create("myfile.xml");  // create reader instance
    
            }
        }
        public class AnotherClass
        {
            SomeClass obj;  // declare variable of type SomeClass
    
            public AnotherClass()  // this is a constructor
            {
                obj = new SomeClass();  // create instance
                obj.TestMethod();  // execute test method
            }
        }



    I used the Code Formatting Tool to post my code.
    It is the icon that looks like this ' </> "

    Rudy  =8^D

    Mark the best replies as answers. "Fooling computers since 1971."
    • Marked as answer by liurong luo Tuesday, March 16, 2010 10:47 AM
    Thursday, March 11, 2010 9:09 PM
  • 1)

      1.1. "XmlReader reader;" is not inheriting. it's declaring an object from XmlReader class named reader and by this declaration it's null
               currently because you don't instant it by new keyword.
      1.2. Yes, it has all methods/properties but they are unusable because it's null currently.

      1.3. Create method is a static method which help you create an instance from XmlReader.

      1.4. It know it's file because the file name is stored in it some where.

    2)

    Yes, some classes doesn't have direct constructor and you should create instance from them by some static methods.


    My Blog - MSDN Complement by providing Visual C# Walkthroughs and Sample Codes - Founded In February 24, 2010
    • Marked as answer by liurong luo Tuesday, March 16, 2010 10:47 AM
    Thursday, March 11, 2010 9:11 PM
  • Sorry, was Rudy and my advices enough?
    If no, please feel free and let us know for more clarification.
    Thanks.
    My Blog - MSDN Complement by providing Visual C# Walkthroughs and Sample Codes - Founded In February 24, 2010
    Thursday, March 11, 2010 9:35 PM
  • Yasser, Rudedog2,

                              Guys thank you for stepping up and helping me on this.  Firstly let me apologise for my poor effort / structure on my initial post - it looks confusing.  RudeDog is right, I feel and know I have missed some fundamental concepts here on a major scale.

    RudeDog, yes I follow your code and understand what is happening but I need to understand the why.



    I will try and explain as I see it......

    1)XmlReader is one of the many classes found in the Base Class Library.  You could call it a XmlReader Class Type, right?


    2)When we do:  XmlReader reader;   we are making  'reader' an Object of XmlReader class type, right?


    3)Doing this is like when we declare a variable:  int myAge;   but this time we are using an object 'int'  Class Type?


    4) Am I correct in saying that the XmlReader declaration is a 'ref' data type and the myAge declaration is a 'value' data type?


    5)  So XmlReader passes on all its properties, fields and methods on to reader but everything has no value or null?  Why are we doing this?
        
         when we get the value of   xmlReader.Create("myfile.xml");   and assign it to 'reader'   what property or field of 'reader' is it held in? 
        
         How does the method in if(reader.read())    know what property or field to look in.



    6)  What is the difference between  doing (if we could) :   XmlReader reader;     or    XmlReader  reader = new reader()  ..... we are not passing parameter so they will be both null and both have the same properties, fields and methods??



    Once again guys thank you for your time.  I am in your debt.

    Cheers.









    Thursday, March 11, 2010 10:21 PM
  • P.S  In  addition to the above reply from me....

    Rudedog said:


    public class AnotherClass
        {
            SomeClassOne obj;  // declare variable of type SomeClass

            public AnotherClass()  // this is a constructor
            {
                obj = new SomeClassTwo ();  // create instance
                obj.TestMethod();  // execute test method
            }
        }








    I have put in One and Two ... would this work? or do they have to be the same type of class?

    In addition  when debugging we are using the CLR but when creating the 'EXE' the compiler? Sorry for all the questions guys.
    • Edited by ukkentlad1980 Thursday, March 11, 2010 10:54 PM Format
    Thursday, March 11, 2010 10:46 PM
  • Hi,

    Abstract Class:
                 C# allows both classes and functions to be declared as abstract.An abstract class cannot be instantiated where as an abstract function doesnt have implementation and must be overriden in any non abstract derived class.

    XmlReader is an abstract class. That means it cant be instantiated.

    When you say "XmlReader reader;" it doesnt actually create any object. Its just a declaration.

    Static Modifier:
               The member doesnt operate on specific instance of the class.

    XmlReader.Create is a static method.

    So you are using "XmlReader reader = XmlReader.Create("test.xml");" to create an object and use it.

    Coming to reader.Read(),it is a method which keeps reading the xml file node by node.

    To the above question you asked:

    1) It doesnt work. They have to be same type.
    2)Your source code is compiled to byte code(CIL code) by C# compiler and then it is converted to Native code by CLR.

    To run on a machine,it has to be in Native code. So your source code is converted to byte code by the compiler and that code is converted to Native code by the CLR on the machine to run it.



     






    • Marked as answer by liurong luo Tuesday, March 16, 2010 10:47 AM
    Friday, March 12, 2010 2:06 PM
  • Yasser, Rudedog2,

                              Guys thank you for stepping up and helping me on this.  Firstly let me apologise for my poor effort / structure on my initial post - it looks confusing.  RudeDog is right, I feel and know I have missed some fundamental concepts here on a major scale.

    RudeDog, yes I follow your code and understand what is happening but I need to understand the why.



    I will try and explain as I see it......

    1)XmlReader is one of the many classes found in the Base Class Library.  You could call it a XmlReader Class Type, right?


    2)When we do:  XmlReader reader;   we are making  'reader' an Object of XmlReader class type, right?


    3)Doing this is like when we declare a variable:  int myAge;   but this time we are using an object 'int'  Class Type?


    4) Am I correct in saying that the XmlReader declaration is a 'ref' data type and the myAge declaration is a 'value' data type?


    5)  So XmlReader passes on all its properties, fields and methods on to reader but everything has no value or null?  Why are we doing this?
        
         when we get the value of   xmlReader.Create("myfile.xml");   and assign it to 'reader'   what property or field of 'reader' is it held in? 
        
         How does the method in if(reader.read())    know what property or field to look in.



    6)  What is the difference between  doing (if we could) :   XmlReader reader;     or    XmlReader  reader = new reader()  ..... we are not passing parameter so they will be both null and both have the same properties, fields and methods??



    Once again guys thank you for your time.  I am in your debt.

    Cheers.

    1) Yes, it's an abstract type in .NET Framework in System.XML. abstract means that you can't have an instance from it and only can inherits from it. so it doesn't have any constructor.

    2) Not making exactly, we declare an object from it which is null currently but can assigned in future codes.

    3) Yes, exactly.

    4) Please see http://msdn.microsoft.com/en-us/library/490f96s2.aspx and also http://msdn.microsoft.com/en-us/library/4d43ts61.aspx

    5) Because you must create an instance from it
        5.1. All of properties/methods.

    6) The difference is the first object is null but the second is not.
    My Blog - MSDN Complement by providing Visual C# Walkthroughs and Sample Codes - Founded In February 24, 2010
    Friday, March 12, 2010 2:10 PM
  • Your last question first.  You must use the same class or type , is the short answer.  Let's postpone the longer answer for now.

    1)  XmlReader is one many types defined within the FCL, Framework Class Library.

    2)  Yes, we are defining a variable named reader of type XmlReader.  Space is created somewhere for this variable name, but the actual variable has not yet been defined and assigned to the variable.  This reference type variable is null at this point.  Instantiating the variable means allocating memory space and filling it with an instance object, an object graph of the type.

    3)  You are using type Int32 to declare your variable myAge.  Substitute the "Int32" in the place of "int" and you will get the same result.  But, note how the two words are displayed in different colors.  Int32 is displayed as cyan because it is a type.  The word "int" is displayed as blue because it is a C# keyword.  A keyword that currently uses the type Int32 to define an Integer.  50 years from now, the keyword might define Int256.

    4)  Yes, XmlReader is a Reference Type, and Int32 is a Value Type.

    5)  In a sense, you might say that XmlReader passes on its' class members to the reader variable.  But, view can lead to misconceptions because not all class members get passed on to an instance object.  The variable actually "Is A" XmlReader instance, an instance object of type XmlReader.

         The method call to CreateReader creates a reader object and returns it to the caller, which means the right side of the equals sign.  It is a special method that is used to construct the highly complex XmlReader object instance.  Normally, we would simply call a constructor much like the ones that I identified in my snippet.  It would seem that XmlReader must require many parameters and probably many steps to fully construct.  They created what is known as a Factory Method to create object instances for us, so that we don't mess it up and re-write our hard drives.

         The XmlReader, like most of the other XXXX Reader types, reads the file sequentially from start to finish.  It does not have random access, and it cannot back up.  It can only move forward.  The Read method directs the XmlReader instance to read the next piece of data out of the file.  Since it is an XmlReader it will read the next XML element.  If it were a TextReader, it would read the next character.

    6)  I think you might be stocked with enough info in this reply to answer this question for yourself. 

    Mark the best replies as answers. "Fooling computers since 1971."
    • Marked as answer by liurong luo Tuesday, March 16, 2010 10:47 AM
    Friday, March 12, 2010 2:21 PM
  • P.S  In  addition to the above reply from me....

    Rudedog said:


    public class AnotherClass
        {
            SomeClassOne obj;  // declare variable of type SomeClass

            public AnotherClass()  // this is a constructor
            {
                obj = new SomeClassTwo ();  // create instance
                obj.TestMethod();  // execute test method
            }
        }
    I have put in One and Two ... would this work? or do they have to be the same type of class?

    In addition  when debugging we are using the CLR but when creating the 'EXE' the compiler? Sorry for all the questions guys.

    Maybe I got what are you trying to ask.
    Please enjoy following sample code ;)
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Windows.Forms;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                AbstractClass ac = new NonAbstractClass1();
                ac.AbstractMethod();
                /*
                 * I guess your question is "how ac knows to call which implementation? implementation #1 or #2?
                 * It knows because it's not really type of AbstractClass, it just a filter!
                 * It's real type is NonAbstractClass1 as you will see in console display
                */
                Console.Write("My real type is: {0}", ac.GetType());
    
                Console.ReadKey();
            }
        }
        abstract class AbstractClass
        {
            abstract public void AbstractMethod();
        }
        class NonAbstractClass1 : AbstractClass
        {
            public override void AbstractMethod()
            {
                Console.WriteLine("I'm abstract method implementation #1.");
            }
        }
        class NonAbstractClass2 : AbstractClass
        {
            public override void AbstractMethod()
            {
                Console.WriteLine("I'm abstract method implementation #2.");
            }
        }
    }

    My Blog - MSDN Complement by providing Visual C# Walkthroughs and Sample Codes - Founded In February 24, 2010
    Friday, March 12, 2010 2:24 PM
  • "A Brief History of Code", by Rudedog Hawkins

    PREFACE:

    Computers began when engineers realized that they could create analog computers that approximated their formulas.  Analog computers were not flexible, because their circuits were built to solve just one type of calculation.  This gave rise to the digital computer, which allowed the programmer to modify the computer behavior by storing "code" within dedicated storage registers.  These registers saved a sequence of instructions that collectively executed a 'procedure' and produced a 'result'.  Engineers could string together many known procedures in a sequence and produce complex results.  The processor would begin with the instruction in the first register, the entry point, and continue on in sequence until it reached the last instruction.

    It quickly became apparent, as the digital computer technology grew by leaps and bounds, that writing code that accurately produced the desired results could be a slow and painstaking process.  Engineers wanted to be able to re-use and combine some of their 'procedures' into larger and more complex programs.  Thus far, engineers had to re-enter the same instructions any time they wanted to re-use proven and tested code.  This problem gave rise to the concept of a 'subroutine'.  Re-usable code was born, that was 'procedure-driven'.  The sub-routine, a basic unit of code that accurateLY produced a result based upon input parameters that were supplied to it.  A sub-routine could be called from one of your main procedures.

    As computer technology grew and grew, engineers set their sights on higher and more complex programs.  Once again, they were driven by the desire to re-use code and that ever present "need for speed" in development.  Whereas they had once wanted to re-use 'procedures', now they wanted to re-use entire programs or just significant portions of them.  This need eventually gave birth to the concept of an "object'.  An object, a unit of code that could execute multiple procedures and sub-routines based upon input parameters that were supplied to it.  It was like a complete little stand-alone program.

    However, the procedures that an object executed were a little different.  It was decided that the procedures that defined an object should be for the exclusive use of that object, not to be shared by other objects.  These procedures were named methods.  But, how do you use these objects?  This is where the constructor comes in. 

    A constructor is the entry point into the code that defines an object.   It is the first method that gets executed, and initializes the object to a pre-determined state.  It is the code that can be modified to accept input parameters to define the behavior of the object over its' lifetime.  Now the concept of the object was complete.  A stand-alone unit of code that was built up from many pieces.  Pieces, which could be easily debugged and proven reliable. 

    But more importantly, the code was easily re-usable by simply calling the object's constructor.  Object Oriented Programming was born.  Objects calling objects inside of other objects.  The best part is this.  You can as many objects as you want of the same type, give each of them different parameters in their constructor, and each of them will be slightly different. 

    For example.  If you had a class named House.  You could give it a constructor that accepted a color.  Now you could define and a declare a Red House, a White House, a Blue House, etc.

    Hope this helps.

    Rudedog Hawkins  =8^D
    Mark the best replies as answers. "Fooling computers since the beginning of Time."
    Friday, March 12, 2010 2:35 PM

  • Stacks and Heaps.

    Imagine a stack of plates, on which you place plates of data.  There are many such stacks used by the .NET Common Language Runtime and the Garbage Collector.  One is called the Managed Heap, which is used by reference types.  The other stack is a smaller one, simply called the Stack and it is used for objects of fixed size like value types and memory pointers.  As you create variables for storage, the type determines where they are stored.  Your methods, functions and subs gain access to the data.

    Identity is determined and defined as the actual storage location.  Equivalence is determined and defined as the data stored at the actual storage location.  That is a subtle, yet significant difference.  Identity is used to describe if objects are identical.  Equivalence is used to describe if objects are equal.

     
    Value Types.

    These are basically all of your numbers.  String class is a special reference type that seems like it wants behave as if it were a value type.  To realize this behavior, strings are treated differently from reference types, and value types, when it comes to memory allocation.  Value types consume a fixed amount of memory.  Memory pointers, IntPtr, are actually Integer types, which means that they also have a fixed size.

    Consider this code using integer variables.

    a = 1
    b = 2
    c = a

    The variable a and c are equivalent but not identical.  They each store the same value in memory, but store their data in different locations.
     

    Reference Types.

    These are basically everything else.  Reference types are for objects or any size, or varying size.  The name comes from how they are treated.  A reference, or memory pointer, is used to identify the object's location on the managed heap.  These references, or pointers, can be used on the stack as if they were value types.  Pointers are fixed in size.  This is how strings are referenced, but there memory storage is immutable.  That means it is not destroyed.

    Consider this code using reference variables, of type Class1.

    a = new Class1
    b = new Class1
    c = a

    The variables store pointers to locations, objects which are placed on the managed heap.  The actual pointers go onto the stack so they can be passed to methods.  The variables a and c are equivalent, and they are identical.  The variable c is assigned the same pointer value as the variable a.  But, variables a and b are equivalent, but not identical!!!



    Mark the best replies as answers. "Fooling computers since 1971."
    Friday, March 12, 2010 2:38 PM