1: 2: 3: 4: 5: 6: 7: 8: 9: |
namespace Test {
public class Accesibility {
private int _private = 10; // this var will be available within this class only
public int _public = 20; // this var will be accessible anywhere
protected int _protected = 30; // this var will be available withi this class and for derived classes
internal int _internal = 40; // this var will be available anywhere within current assembly
protected internal int _protected_internal = 50; // this var available within current assembly and for derived classes
}
}
|
`
Once a class implements an interfaces it takes responsibility to provide functionality declared by interface.
1: 2: 3: 4: 5: 6: |
public interface ISomeInterface1 {
void SomeMethod(); // declare a method
int SomeProperty {get; set;} // declare a property
event EventHandler SomeEvent; // declare an event
int this[string index] {get; set;} // declare an indexer
}
|
Class might implement interface in 2 ways:
Rules of thumb
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: |
class Counter {
private int _id, _i;
private static int s_n;
public Counter() {
_id = s_n++;
}
public void Increment() {
Console.WriteLine(“{0} -> {1}”, _id, ++_i);
}
public void Decrement() {
Console.WriteLine(“{0} -> {1}”, _id, —_i);
}
public int Count
{
get { return _i; }
}
}
|
There are 2 kind of inheritance in C#:
Inheritance allows child classes inherit characteristics and behaviour of parent class:
Inheritance allows child classes extend characteristics and behaviour of parent class:
A class can inherit only one class (singular implementation inheritance)
Class can be derived from only one parent class.
1:
|
public class DerivedClass : BaseClass
|
Interfaces can extend multiple interfaces
1:
|
public interface IDerived : IBase1, IBase2
|
Class can implement multiple interfaces
1: 2: |
public class DerivedClass : IBase1, IBase2
public class DerivedClass : IBase1, IBase2
|
Examples:
base and this keywords allow developer to refer to another constructor declared in base of current class
In static polymorphism, the decision is made at compile time.
1:
|
public virtual void VirtualMethod()
|
member hiding is when you declare member with the same name in derived class
hiding of a virtual member breaks the polymorphism (and compiler will show you a warning in this case).
To force hiding virtual member, keyword new is used:
1:
|
public new void VirtualMethod() {...}
|
Hidden member could be also marked as virtual and start another chain of polymorphism:
1:
|
public new virtual void VirtualMethod() {...}
|