What's the purpose of Shadowing? - c#

I recently read an article about shadowing or hiding in programming (C++, C#, VB).
But I still don't get what's the reason of those? Why would we do something like that? I mean we can always call the real function if we want it to return the value, and not casting some class to it.
Well, I am not much a very very good at programming so I can't see the reason:)
Anyone can explain?
Thank you

In shadowing the child class has its own version of the method providing different implementation, the same method is also available in the base class.
Suppose you have class library being used by various modules in a project. There is a method which is being referenced other libraries. if we make a change in method it may break existing functionality. Hence we hide/shadow the method using new keyword. This way we are able achieve new functionality without breaking old functionality.
EDIT:
You can also find a great example on Eric Lippert's blog here.

Related

Can I rebuild .NET class from reference source?

I want to add some methods in System.Net.HttpWebRequest class to suit my needs. I tried reflection but it is quite complicated that I need to alter many of its member class method as well.
I am debugging through .NET reference source and I could view the source code of those class. Is it possible for me to copy each of the related class source code and build my own class?
For some classes yes, but for many no.
.NET classes frequently use internal classes that are not exposed publicly, you would not only need to rebuild the class you are interested in but also rebuild all internal references too.
I would recommend not trying to do this and instead either using Extension Methods or if that does not solve your problem ask a new question describing the exact thing you are trying to accomplish and perhaps we can show you a easier way to do it.
Anything's possible.
You have the source code. You know how to copy and paste. Certainly it's possible you could adapt that code for your own purposes.
The question is; is it legal?
To answer that, you need only examine the license for the reference source. To that end, it's perfectly legal, assuming you comply with the MIT license (which is pretty lenient).
The next question is; should you? Probably not. Most likely, you could just add your desired functionality via a helper class or child class, or add new methods via Extension Methods.

can csharp classes "inherit" the xml documentation like java classes can?

i'm adding comments to some csharp code, and i'm using the xml language provided by .net (or something). i have an interface, and some implementing classes. i have one method in the interface, and it has a comment. in the implementing classes there is no comment on the implementing method.
when one does it like this in java, javadoc automagically uses the interface comment when generating documentation. however, now that i build my project, i get the warning (transalted from swedish, sorry) "the xml comment for the visible type or member bla.blabla.blablabla() is missing (cs1591)". this is only a warning, so not so bad. but!!! it means no xml file was output, so i can't use sandcastle to generate a chm document file, which is my real goal here.... googling the error coded gave nothing :(
do i really have to copy the method comment to all implementing classes? that's like.... code duplication D: is there no way to get the behavior java offers?
I don't know of any way of getting it to happen at XML file generation time, but GhostDoc may well save you from performing the copying manually. I can't say I've used it myself though.
I agree that it would be a valuable feature... particularly if the base class (or interface) documentation changes after the derived classes have been implemented and documented.
You do have to copy the interfaces comments to the implementing class. Generally this is a good thing as the two comments should ideally be different - my opinion (and practise) on this can be summarised as the following:
Interface Comments - Explains what the method/property/etc is supposed/expected to do but should generally not proscribe how any specific implementation should behave
Implementing Class Comments - Explains what the method/property/etc actually does and may include some details of how this is done (typically in <remarks>)
VSdocman can resolve missing XML comments from implemented interfaces automatically when it generates documentation. Moreover, like GhostDoc, it can also explicitly copy inherited comments to the implementing method. Unlike Sandcastle, it's not free.
Well i dont know about Java but Sorry you will have to copy the interface's comments in the implemented class. here is no inbuilt way of doing it...
And yeah consider the suggestion given by JonSkeet

Are extension methods an object-oriented feature of C#?

Do extension methods follow the object-oriented paradigm in C#?
Is it a good practice to use extension methods?
In the software development lifecycle how should we consider this question in the design phase?
Eric Lippert has blogged about this and I suspect I can't do much better than to quote him:
So, yes, the oft-heard criticism that
"extension methods are not
object-oriented" is entirely correct,
but also rather irrelevant. Extension
methods certainly are not
object-oriented. They put the code
that manipulates the data far away
from the code that declares the data,
they cannot break encapsulation and
talk to the private state of the
objects they appear to be methods on,
they do not play well with
inheritance, and so on. They're
procedural programming in a convenient
object-oriented dress.
They're also incredibly convenient and
make LINQ possible, which is why we
added them. The fact that they do not
conform to some philosophical ideal of
what makes an object-oriented language
was not really much of a factor in
that decision.
I would add, however, that they're useful beyond just LINQ - for the same reason that they're useful in LINQ. It's really nice to be able to express algorithms which work on arbitrary implementations of a particular interface (such as IEnumerable<T> in LINQ to Obhects). Such algorithms typically don't have any context beyond the interfaces you're working on, so they're often naturally static.
If you accept that you've got some static utility method, which syntax would you rather use?
// Traditional
CollectionUtils.Sort(collection);
// Extension methods
collection.Sort();
The latter is simply more readable in my opinion. It concisely expresses what you want to do. It doesn't make it clear how you want to do it, but that's less important for most of the time - and more important when you're debugging that particular line, of course.
Extension methods are not an object oriented language feature. (compared to: classes, inheritance, polymorphism etc).
Like every language feature, it should be used where it is appropriate and for what it is designed for. There are already dozens of questions about when and how to use Extension methods.
What are the best practices for using Extension Methods in .Net?
Possible overuses of Extension Methods
Do Extension Methods Hide Dependencies?
There are two parts to it.
Is it OO when we use it
No; it makes you feel that you are calling method on the particular type
Is it OO based on how it is compiled/built
Yes; Compiled code has a static method using the object on which extension method was invoked
Extension methods are just a language feature. They work on object instances and are very nice tool.
Consider them as a different way to extend class functionality. You can add new functionality to a class:
By adding a partial class declaration. The class then instantly gets a bunch of new methods and properties.
By including a namespace with your extension methods holder class. The class then gets a bunch of new methods again.
Rather an organizational / language feature. Does not break object-oriented concept in any way. Just as header/source file division in C/C++ has nothing to do with object-orientation, just a language/framework feature.
It depends. Extension methods are just a tool. They can be very useful when used appropriately. But if you use them too much, it can obscure your code.
Extension Methods are just static methods that work with a specific Class or Class Hierarchy. Python is OO but has modules, Ruby has mixins. I see it more as a language feature. I am pretty sure its still OO friendly

Are C# extension methods only available for instance methods?

I have recently started to make useful use of C# extension methods. The SO examples and the documentation suggest that they are only used for instance methods (i.e. with the this keyword). It is possible to use them (or another approach) with static/class methods?
(My particular requirement is converting Java code to C# where "most of the code" does not need editing. The Java instance methods (e.g. Java String.indexOf()) can be routed through an extension method calling C# string.IndexOf()). I would like to do the same for, say, Java Math.abs() => C# Math.Abs()).
SUMMARY No. The answers suggest it would be a reasonable thing to have but it's unlikely to happen soon. Workarounds will require editing creating new classes or something similar and may not be worth it.
You cannot create static extension methods - it's also something I've wished to be able to do!
You could create your own static classes with a standard suffix, i.e. MathJSyntax.abs(..) which would call Math.Abs(..)
C# 3.0 does not allow the creation of static extension methods, unfortunately. F# however does allow this, along with the much desired feature of extension properties.
The notation itself doesn't let you do it, the "this" class parameter expects an instance to the class to be passed in. If they intended to at least eventually add it, they wouldn't have written it like that.
So the short answer is nope, and never will be!

evaluating cost/benefits of using extension methods in C# => 3.0 [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
In what circumstances (usage scenarios) would you choose to write an extension rather than sub-classing an object ?
< full disclosure : I am not an MS employee; I do not know Mitsu Furota personally; I do know the author of the open-source Componax library mentioned here, but I have no business dealings with him whatsoever; I am not creating, or planning to create any commercial product using extensions : in sum : this post is from pure intellectal curiousity related to my trying to (continually) become aware of "best practices" >
I find the idea of extension methods "cool," and obviously you can do "far-out" things with them as in the many examples you can in Mitsu Furota's (MS) blog postslink text.
A personal friend wrote the open-source Componax librarylink text, and there's some remarkable facilities in there; but he is in complete command of his small company with total control over code guidelines, and every line of code "passes through his hands."
While this is speculation on my part : I think/guess other issues might come into play in a medium-to-large software team situation re use of Extensions.
Looking at MS's guidelines at link text, you find :
In general, you will probably be
calling extension methods far more
often than implementing your own. ...
In general, we recommend that you
implement extension methods sparingly
and only when you have to. Whenever
possible, client code that must extend
an existing type should do so by
creating a new type derived from the
existing type. For more information,
see Inheritance (C# Programming
Guide). ... When the compiler
encounters a method invocation, it
first looks for a match in the type's
instance methods. If no match is
found, it will search for any
extension methods that are defined for
the type, and bind to the first
extension method that it finds.
And at Ms's link text :
Extension methods present no specific
security vulnerabilities. They can
never be used to impersonate existing
methods on a type, because all name
collisions are resolved in favor of
the instance or static method defined
by the type itself. Extension methods
cannot access any private data in the
extended class.
Factors that seem obvious to me would include :
I assume you would not write an extension unless you expected it be used very generally and very frequently. On the other hand : couldn't you say the same thing about sub-classing ?
Knowing we can compile them into a seperate dll, and add the compiled dll, and reference it, and then use the extensions : is "cool," but does that "balance out" the cost inherent in the compiler first having to check to see if instance methods are defined as described above. Or the cost, in case of a "name clash," of using the Static invocation methods to make sure your extension is invoked rather than the instance definition ?
How frequent use of Extensions would affect run-time performance or memory use : I have no idea.
So, I'd appreciate your thoughts, or knowing about how/when you do, or don't do, use Extensions, compared to sub-classing.
thanks, Bill
My greatest usage for them is to extend closed-off 3rd party APIs.
Most of the time, when a software developer is offering an API on Windows these days, they are leaning more and more toward .NET for that extensibility. I like to do this because I prefer to depend on my own methods that I can modify in the future and serve as a global entry point to their API, in the case that they change it.
Previously, when having to do this, and I couldn't inherit the API object because it was sealed or something, I would rely on the Adapter pattern to make my own classes that wrapped up their objects. This is a functional, but rather inelegant solution. Extension methods give you a beautiful way to add more functionality to something that you don't control.
Many other peoples' greatest usage for them is LINQ!
LINQ would not be possible without the extension methods provided to IEnumerable.
The reason why people love them is because they make code more readable.
I have noticed another MAJOR usage of extension methods (myself included) is to make code more readable, and make it appear as if the code to do something belongs where it is supposed to. It also gets rid of the dreaded "Util" static-god-class that I have seen many times over. What looks better... Util.DecimalToFraction(decimal value); or value.ToFraction();? If you're like me, the latter.
Finally, there are those who deem the "static method" as EVIL!
Many 'good programmers' will tell you that you should try to avoid static methods, especially those who use extensive unit testing. Static methods are difficult to test in some cases, but they are not evil if used properly. While extension methods ARE static... they don't look or act like it. This allows you to get those static methods out of your classes, and onto the objects that they really should be attached to.
Regarding performance..
Extension methods are no different than calling a static method, passing the object being extended as a parameter... because that is what the compiler turns it into. The great thing about that is that your code looks clean, it does what you want, and the compiler handles the dirty work for you.
I use extension methods as a way to improve the functionality for classes without increasing the complexity of the class. You can keep your classes simple, and then add your repetitive work later on as an extension.
The Min() and Max() extension methods are great examples of this. You could just as easily declare a private method that would calculate these, but an extension method provides better readability, makes the functionality available to your entire project, and didn't require making an array any more complex of an object.
Taking the sub-classing approach vs. extension methods requires a couple of things to be true
The type must be extendable (not-sealed)
All places the type is created must support a factory pattern of sorts or the other code will just create the base type.
Adding an extension method requires really nothing other than using a C# 3.0+ compiler.
But most importantly, an inheritance hierarchy should represent an is-a relationship. I don't feel that adding 1 or 2 new methods / behaviors to a class truly expressing this type of relationship. It is instead augmenting existing behavior. A wrapper class or extension method much better fits the scenario.
In some cases you can't use a subclass: string for instance is sealed. You can however still add extension methods.

Categories

Resources