Some keywords related to Object Oriented Programming are explained here.
public vs protected vs private
- public: Any class can refer
- protected: Can be inherited
- private: Cannot be inherited
The default is private!
internal
If internal is defined in a dll; any exe which uses the dll can’t access it.
Example:
protected internal
static
- Static methods can be used without creating an object.
- Static methods must be called using class name, not using object name!
const vs readonly
- For the readonly keyword, the latest value is known by the runtime.
- For the const keyword, the value must be known by compile time.
overload
- Same name, different parameters.
- Overloading is an example of polymorphism.
ref vs in vs out
- ref is used to state that the parameter passed may be modified by the method.
- in is used to state that the parameter passed cannot be modified by the method.
- out is used to state that the parameter passed must be modified by the method.
ref must have default value, out doesn’t need to have default value!
get vs set
In order to access a private value;
- Define a public method
- Define get and set
class Person
{
private string name; // field
public string Name // property
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
this
The this keyword refers to the current object (instance) of the class and is also used as a modifier of the first parameter of an extension method.
Creator Method
- The creator method must be public.
- The creator method doesn’t return value.
Destructor Method
- ~ is used
C++ example:
class Test
{
public:
Test()
{
count++;
cout<<"\n No. of Object created:\t"<<count;
}
~Test()
{
cout<<"\n No. of Object destroyed:\t"<<count;
--count;
}
};
Inheritance related keywords
- If you define a virtual method and inherit from it, then you can change it using override.
- An abstract class can’t create objects.
- A sealed modifier prevents other classes from inheriting from it.
- In Java all of methods are virtual by default. And methods in derived classes override methods from base. In C# they are not.
base
The base keyword is used to access members of the base class from within a derived class.