C# Object Oriented Approach

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dotnetnovice
    New Member
    • Aug 2009
    • 21

    C# Object Oriented Approach

    Hi...I am new to object oriented programming and facing a problem with classes and inheritance.
    My question is how to call members of one class in to another class.

    Here is class 1
    Code:
    class Class1 
        {
            public string Id;
            public string Name;
    
            public Class2 Add;
        }
    Here is Class 2
    Code:
    class Class2 
        {
            public string Address;
        }
    But when i call it as
    Code:
     Class1 a = new Class1();
                a.Id = "1";
                a.Name ="abc";
                a.Add.Address = "def";
    The compiler gives error like null reference

    Please help

    Thanks
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    With the code you've posted, you're not doing inheritance. The reason you're getting the null reference is because no instance of Class2 has been created in Class1, it is in fact null. This is a compiler default... numbers default to zero, strings to "", and references to null.

    To fix the immediate problem, you'd need to instantiate a new Class2 in Class1 either in the constructor, or right at the declaration (the compiler lets you do this).

    Code:
    class Class1 
        {
            public string Id;
            public string Name;
     
            public Class2 Add = new Class2();
        }
    ... or ...

    Code:
    class Class1 
        {
            public string Id;
            public string Name;
     
            public Class2 Add;
    
            public Class1() { Add = new Class2(); }
        }
    Now, if you want inheritance, you have to tell Class1 to inherit Class2, as such...

    Code:
    class Class1 : Class 2 { ... }
    Here's a link to a tutorial on inheritance.

    Comment

    • tlhintoq
      Recognized Expert Specialist
      • Mar 2008
      • 3532

      #3
      Here is another tutorial that shows the making of an application from scratch, including inheritance.

      But as Gary pointed out, when you are making your variables you are not initializing them. That is a bad habit to get into. You should always initialize them to *something*. Some people initialize variables to values they know will work (default values). Others tend to make them values they know to look for. For example, if you know a valid range for you application is 0-10, initialize to -1. That way you check if the variable is still -1, meaning the user didn't input anything.

      Comment

      Working...