Can you explain one
practical scenario when we should use partial class?
Let’s say our company want to create thousands of different Mathematical functions. Now the issue is if only person start working on it, it will take more time to complete. But company needs it quickly. So the best solution is parallel development, More than one developer will make them indulged into same task. Well now what? Does everyone go and create their own class? If yes it will end up with new issue, Especially Code Management issue.
So the next solution is Partial class which will let us spilt our class definition across multiple locations.
At the end everything will merge up together and considered as one.
Is this the only advantage
of Partial class?
No sometimes just to keep things simpler and cleaner
sometimes we would like to put some part of the file in another file but still
want to consider both parts as one. Our major requirement keep it simple.
When partial method comes
handy?
Let’s say,
as discussed earlier 2 developers are working on same class with the help of
partial class.
Now
developer 1 want to use one logic which is going to be created by Developer 2
in his partial class.
Now the
issue is right now Developer 1 can’t access the functionality created by
Developer 2 (because Developer 2 didn’t committed his changes yet). So what
developer 1 will do is he will create partial method in his partial class with
return type as void and Developer 2 will define that method in his partial
class.
//Developer 1
publicpartialclass
Maths
{
partialvoid
Logic1();
publicvoid
Logic2() { Logic1();}
}
|
//Developer 2
publicpartialclass
Maths
{
partialvoid
Logic1(){}
publicvoid
Logic4 () {
/*....*/
}
}
|
This question is taken from the
.NET interview questions with answer book written by Shivprasad koirala.
Below is a nice c# Partial class interview question video which explains the concept practically.