0

I found C# very interesting...but unfortunately (or fortunately ! ) it has many features to implement OOP rules....they have different machanisms and make me sometimes confused....

virtual, new,... modifiers in c# have different rules....so what is the best way or best-practices for learning OOP rules and use them easily...?

so what is the best way or best-practices for learning OOP rules and use them easily...?

AminM
  • 1,658
  • 4
  • 32
  • 48
odiseh
  • 25,407
  • 33
  • 108
  • 151

2 Answers2

3

The best way to learn is to keep things simple and practice (program) a lot. Regarding virtual/new/override, there are three main cases:

  1. Virtual + override - Use virtual in the base class and override in the derived class, as in:

    class BaseClass  
    {      
         public void virtual Test(){...}  
    }  
    class DerivedClass: BaseClass  
    {  
        public void override Test(){...}  
    }
    
  2. Abstract + override - This is a variant of the previous case where the base member does not define a body:

    abstract class BaseClass
    {
        public void abstract Test(){...}
    }
    class DerivedClass: BaseClass
    {
        public void override Test(){...}
    }
    
  3. No modifier - This is useful when you don't plan on overriding a method:

    class BaseClass
    {
        public void Test(){...}
    }
    class DerivedClass: BaseClass
    {
        public void OtherMethod(){...}
    }
    

    In the this case, there would be a warning if OtherMethod was named Test. Indeed, it would clash with the base method. You can get rid of the warning by adding a new modifier as in

    abstract class BaseClass
    {
        public void Test(){...}
    }
    class DerivedClass: BaseClass
    {
        public new void Test(){...}
    }
    

    However, I would recommend avoiding the new modifier if possible since it is somewhat confusing.

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
pn.
  • 852
  • 1
  • 8
  • 9
  • yeah, as you said, we can use override modifier in the last case you wrote instead of using new just for running method of derived class... if so, what's the main difference between using override and using new ? – odiseh Jul 01 '09 at 04:33
  • You cannot use override unless the base is either virtual or abstract – pn. Jul 01 '09 at 07:16
2

Your best bet is to learn about OOP principles (encapsulation, inheritance and polymorphism) from a fundamental source. And then worry about particular language implementations later. Once you really understand the fundamental concepts, the language specifics become easy to learn, apply and master.

JP Alioto
  • 44,864
  • 6
  • 88
  • 112