Structures
This concept is not new in C#; it is taken from C language. In C language‘s structures, you can write only some member variables, called as "data members" / "fields". But in C#‘s structures, you can write fields along with some methods also. So, In C#, structures are almost all similar to the classes, but having some differences with the classes.
Implementation:
- Define structure
struct structurename
{
//fields
//methods
}
- Create instance for structure
structurename instancename = new structurename();
Download above Code for Demo on Structure : Downloads Links
Extension Methods
This is concept is meant for extending the methods of a class.
There are two ways to extend a class:
- Inheritance
- Extension Methods
- As you know already in "inheritance", you can extend the features of a class by defining derived class.
- But in this "inheritance" feature, you are creating two classes (base class and derived class).
- But, if you want to add a method to an existing class, that is accessible with the objects of the same class, it is not possible in "inheritance". But it is possible using "Extension Methods".
- Conclusion: This feature allows you to add one or more new methods to the same class, without changing the definition of that particular class.
- This is more useful, when you want to add more methods to a pre-defined class.
- When you want to implement this concept practically, simply take a new static class first.
- In this static class, write a static method, with the required name.
- In that method, the first argument should be like this:
this classname argumentname
- Here, in place of "classname", specify the class name, for which you want to write the extension method.
- Then the "argument name" acts as "this" pointer in the code.
Note: Even though it is defined as a "static method" it is accessible as a non-static method from the object of the source class.
Syntax:
public static return_type method_name(this class_name arg, <other args if any>)
{
//some code
}
Limitation: You can‘t add a static method for an existing class.
No comments:
Post a Comment