For some unknown reason I have decided to make some sausages with my pasta tonight and write couple of line about Class definitions in C#. I hated the smell of sausages and just decided to have my pasta with parmesan cheese and tomato sauce. It is really sucks when I am alone and need to cook something.
This is handy dandy to make some relation between C# class definitions and the design patterns actually. It is like making a relation between parmesan cheese and pasta, or perhaps between pasta and parmesan cheese. But because I am starving, I would probably leave the design patterns stuff to some next stage.
Abstract Class
Abstract class is a base class. It can not be instantiated. It is mainly used for inheritance. Abstract class may or may not have implementation. So a sub classes which are inheriting from main class can override methods and property of the main class.
publicabstractclass SampleClass
{
publicabstractvoid SampleMethos(int param);
}
Overriding the methods:
publicclass SubClass : SampleClass
{
publicoverridevoid SampleMethod(int param)
{
//[ToDo] implementation.
}
}
Abstract Class vs Interface
There is an absolute fact that Interface doesn’t have any implementation. But Abstract class, could have.
Remember the new Keyword. You could use it as a modifier to hide inherited member from the base class and provide new implementation.
Sealed Class
The concept is defining a class which no one can inherit from. It seled so it used to prevent inheritance. The usage might be the time that you have static members:
sealed classSampleSealedClass
{
publicstatic intMultiply(int x, int y)
{
return x * y;
}
}
Static Class
A Class which can not be instantiated. It contains static members only. We might define private constructor for static class to be able to prevent automatic generation of default constructor.
staticclass SampleStaticClass
{
publicstaticstring GetSiteName() { returnConstants.SiteName; }
}
Sealed vs Static Class
- Static Class cannot be instantiated but Sealed class can.
- Within Static class only static members are allowed. So static class can only have static constructor to initialize static members
- You can not inherit from either a Sealed class or a Static class
Partial Class
Partial keyword let you split up the class implementation. It is make a lot scene especially when a part of implementation has been generated by any ORM tool.
publicpartialclass Products
{
publicvoid GetProductByID()
{
//implementation
}
}
publicpartialclass Products
{
publicvoid GetProductByName()
{
//implementation
}
}