Hi ahmedsalah, there do exits some differences between keyword override and new. In daily coding, we dont recommend you use keyword **new**. The biggest difference between override and new is that once you "new" a method in derived class, you can
t use polymorphism anymore.
In other words, if you use the same method name in base class to "new" a method in derived class, the method in base class can still work as it defined in base method. However, if you use the same method name in base class to "override" a method in derived class, the method in base class can only work as it defined in override method. To make it more understandable, here`s some codes for you:
- Override
public class C1 { public virtual string GetName() { return "AHMEDSALAH"; } } public class C2 : C1 { public override string GetName() { return "ahmedsalah"; } } C1 c1 = new C1(); Console.WriteLine(c1.GetName());//Output “AHMEDSALAH” C2 c2 = new C2(); Console.WriteLine(c2.GetName());//Output “ahmedsalah” //Here`s the point!!! C1 c3 = new C2(); Console.WriteLine(c3.GetName());//Output “ahmedsalah”
- New
public class C1 { public virtual string GetName() { return "AHMEDSALAH"; } } public class C2 : C1 { public new string GetName() { return "ahmedsalah"; } } C1 c1 = new C1(); Console.WriteLine(c1.GetName());//Output “AHMEDSALAH” C2 c2 = new C2(); Console.WriteLine(c2.GetName());//Output “ahmedsalah” //Here`s the point!!! C1 c3 = new C2(); Console.WriteLine(c3.GetName());//Output “AHMEDSALAH”
In the codes above, I believe you can understand the difference between keyword override and new.
In summary, you can override many methods in different derived class and when you use derived class to new a base class, like C1 test = new C2(), you can only use the method in derived class. If you new method in derived class, you can use base method when you use derived class to new a base class.
Besides, you need to pay attention to conditions in which you can use override (virtual method or blah blah...)
So here`s the Microsoft doc link for details of override in C#, hope can help you more: override
If you still feel confused, please comment and we can discuss more. If you feel helpful from my answer, please accept it and vote for it!