How Do I Handle Conflicts in Overloaded Method Signatures? - c#

I have a feeling this question is a can of worms but I am going to ask anyway... :)
I have a method:
private MembershipUser GetUserFromReader(SqlDataReader reader)
And I want overload this method with a different return type:
private User GetUserFromReader(SqlDataReader reader)
But the compiler complains that the two methods have the same signature.
So, what is the best way to do this? I would prefer to not add an unnecessary
parameter just to change the method signature.
I have played with the idea of doing something like:
private User GetUserFromReader(T reader)
But haven't really explored this in full yet. It seems like I'll need to make a
bunch of changes with how I use my reader object.
Any ideas? What is the best practice when you have two overloaded
methods of the same signature?
Thanks for helping out...

Why overload it? Why not just let the method say what it does, like so:
private MembershipUser GetMembershipUserFromReader(SqlDataReader reader)
private User GetUserFromReader(SqlDataReader reader)

If you really want to differentiate the return type, but use the same method signature, you could use generics:
private T GetUserFromReader<T>(SqlDataReader reader)
But it's much simpler to just rename the methods, as in Luhmann's answer.

Your only real options are:
Change the name of the function
Change the signature of the function
I hate to be trite, but there isn't a way around the restriction on differentiating methods solely by return type.
If one of the overloads is declared in a parent class then you can use the new keyword to "hide" the higher method from callers, but new (on a member declaration) is usually considered evil.

You can't change the return type on an overload. How is the compiler supposed to tell which one you want to use?
What you should do is return a common superclass of everything you might want to return, and then just return whatever is applicable.
Either that, or name the methods differently, since they clearly do different things.

The simple answer is that, as far as C# is concerned, you can't. Overloading by return type is permitted (I think) by MSIL, but not by C#.
The only real choice (i.e, excluding adding a "dummy" parameter), is to call one method GetMembershipUserFromReader and the other GetUserFromReader

Related

Why do we need C# delegates

I never seem to understand why we need delegates?
I know they are immutable reference types that hold reference of a method but why can't we just call the method directly, instead of calling it via a delegate?
Thanks
Simple answer: the code needing to perform the action doesn't know the method to call when it's written. You can only call the method directly if you know at compile-time which method to call, right? So if you want to abstract out the idea of "perform action X at the appropriate time" you need some representation of the action, so that the method calling the action doesn't need to know the exact implementation ahead of time.
For example:
Enumerable.Select in LINQ can't know the projection you want to use unless you tell it
The author of Button didn't know what you want the action to be when the user clicks on it
If a new Thread only ever did one thing, it would be pretty boring...
It may help you to think of delegates as being like single-method interfaces, but with a lot of language syntax to make them easy to use, and funky support for asynchronous execution and multicasting.
Of course you can call method directly on the object but consider following scenarios:
You want to call series of method by using single delegate without writing lot of method calls.
You want to implement event based system elegantly.
You want to call two methods same in signature but reside in different classes.
You want to pass method as a parameter.
You don't want to write lot of polymorphic code like in LINQ , you can provide lot of implementation to the Select method.
Because you may not have the method written yet, or you have designed your class in such a way that a user of it can decide what method (that user wrote) the user wants your class to execute.
They also make certain designs cleaner (for example, instead of a switch statement where you call different methods, you call the delegate passed in) and easier to understand and allow for extending your code without changing it (think OCP).
Delegates are also the basis of the eventing system - writing and registering event handlers without delegates would be much harder than it is with them.
See the different Action and Func delegates in Linq - it would hardly be as useful without them.
Having said that, no one forces you to use delegates.
Delegates supports Events
Delegates give your program a way to execute methods without having to know precisely what those methods are at compile time
Anything that can be done with delegates can be done without them, but delegates provide a much cleaner way of doing them. If one didn't have delegates, one would have to define an interface or abstract base class for every possible function signature containing a function Invoke(appropriate parameters), and define a class for each function which was to be callable by pseudo-delegates. That class would inherit the appropriate interface for the function's signature, would contain a reference to the class containing the function it was supposed to represent, and a method implementing Invoke(appropriate parameters) which would call the appropriate function in the class to which it holds a reference. If class Foo has two methods Foo1 and Foo2, both taking a single parameter, both of which can be called by pseudo-delegates, there would be two extra classes created, one for each method.
Without compiler support for this technique, the source code would have to be pretty heinous. If the compiler could auto-generate the proper nested classes, though, things could be pretty clean. Dispatch speed for pseudo-delegates would probably generally be slower than with conventional delegates, but if pseudo-delegates were an interface rather than an abstract base class, a class which only needs to make a pseudo-delegate for one method of a given signature could implement the appropriate pseudo-delegate interface itself; the class instance could then be passed to any code expecting a pseudo-delegate of that signature, avoiding any need to create an extra object. Further, while the number of classes one would need when using pseudo-delegates would be greater than when using "real" delegates, each pseudo-delegate would only need to hold a single object instance.
Think of C/C++ function pointers, and how you treat javascript event-handling functions as "data" and pass them around. In Delphi language also there is procedural type.
Behind the scenes, C# delegate and lambda expressions, and all those things are essentially the same idea: code as data. And this constitutes the very basis for functional programming.
You asked for an example of why you would pass a function as a parameter, I have a perfect one and thought it might help you understand, it is pretty academic but shows a use. Say you have a ListResults() method and getFromCache() method. Rather then have lots of checks if the cache is null etc. you can just pass any method to getCache and then only invoke it if the cache is empty inside the getFromCache method:
_cacher.GetFromCache(delegate { return ListResults(); }, "ListResults");
public IEnumerable<T> GetFromCache(MethodForCache item, string key, int minutesToCache = 5)
{
var cache = _cacheProvider.GetCachedItem(key);
//you could even have a UseCache bool here for central control
if (cache == null)
{
//you could put timings, logging etc. here instead of all over your code
cache = item.Invoke();
_cacheProvider.AddCachedItem(cache, key, minutesToCache);
}
return cache;
}
You can think of them as a construct similar with pointers to functions in C/C++. But they are more than that in C#. Details.

c# parameters question

I am new to c# and need help understanding what going on in the following function
public bool parse(String s)
{
table.Clear();
return parse(s, table, null);
}
where table is a Dictionary. I can see that is is recursive but how is parse being passed three params when it is defined to take just a string?
EDIT: how do I delete a question? parse has been overloaded facepalm
it is overloaded parse exists that accepts 3 arguments.
No, it is not recursive.
It's a totally different function.
In C#, and also C++, different functions can have the same name. This is called 'overloading'
There has to be another definition in your code that has a parse method that accepts three parameters. Right click on the "parse" on the line with the return and select "Go to Definition" in visual studio to find it.
Method overloading in class based Object Oriented Languages is a very helpful tool. Methods are like functions (they have parameters, they return a value unless they are void and they do some things), but they are part of a class (if they are static) or an object. A method is identified by a method signature. If you define two methods with the same name for a class or the objects of the class, but the parameter list is different, they become two different methods, with the same name.
Benefits:
1.) If some methods are basically doing the same, you'll know from the start this, because you give them exactly the same name.
2.) You can use overloading to solve many problems in a simple way which are very difficult to manage under languages like C.
Recursivity would happen if you called parse("foo") there, because that would call the same function.
The parse function is overloading. In overloading same function can do different work depend upon parameter.
Second parse method excepting 3 arguments.

Why can't an Anonymous Type be used outside the method it's created in?

I understand that if I cast it to a named type I can do whatever I want with it, but it'd make for much tidier code if I could keep the anonymity between method calls.
Think of the signature of your method as a contract. Your method says "I promise to return you something that contains the following fields." If you return an anonymous object from your method, there's no contract. You're just saying "There's some data here, good luck!"
If C# 4 is at all an option, you can just use tuples to return somewhat more arbitrary data.
While it should be avoided because it isn't very clean, you might consider this hack from Jon Skeet. However, if at all possible, it should be avoided.
This is a guess...but I'm so "awesome" I'm "sure" I'm right...
Anonymous types really aren't "anonymous." The class that represents the unknown type is generated at run-time local to the method call on the run-time stack(hence the method-only scope). Returning from the function call(popping the stack) you lose all the objects in that scope including the anonymous class that was hiding on the stack with that method call.
Guessing over...

Method overloads and code duplication promotion

Overloaded methods tend to encourage a habit of duplicating the code between all methods of the method group. For example, I may concat a string, write it to file, etc in one method but then do the same in another method but with the addition of an additional parameter (Creating the overload).
The methods themselves could go in a base class which will make the concrete class look cleaner but the base class will have the problem then (working around the problem). The params keyword seems like a solution but I can imagine if I really think this idea through (using params rather than individual parameters), there'll be some sort of other issue.
Am I therefore the only one to think that overloads promote code duplication?
Thanks
Usually I'd have the actual implementation in the overload with the most parameters, and have the other overloads call this one passing defaults for the parameters which aren't set.
I certainly wouldn't be duplicating code which writes to a file across different overloads - in fact, that code alone could probably be refactored out into its own properly parameterized private method.
In addition to the options above, upcoming in the new version of c# is default parameter capabilities, which is basically just syntatic sugar for what Winston suggested.
public string WriteToFile(string file, bool overWrite = false){
}
A common pattern that more or less eliminates this problem is to have one base implementation, and have each overload call the base implementation, like so:
string WriteToFile(string fileName, bool overwrite) {
// implementation
}
string WriteToFile(string fileName) {
WriteToFile(fileName, false);
}
This way there is only one implementation.
If all of the overloads use the same code, they just handle it slightly differently, perhaps you should either make another function that each overload calls, or if one of them is a base, generic version, then each of the other overloads should call the generic one.

Use of extension methods to enhance readability

What is the general thinking on the use of extension methods that serve no purpose other than enhancing readability?
Without using extension methods we might have the method
IEnumerable<DependencyObject> GetDescendents(DependencyObject root) {}
that could be called with
var descendents = GetDescendents(someControl);
or
foreach (var descendent in GetDescendents(someControl)) {}
Although there's nothing wrong with this I find the instance.method() notation to be more readable so I might consider making this an extension method with this signature
public IEnumerable<DependencyObject> GetDescendents(this DependencyObject root) {}
allowing it to be called with
var descendents = someControl.GetDescendents();
or
foreach (var descendent in someControl.GetDescendents()) {}
So my question is whether you think this is reasonable or an abuse of extension methods. If it was simply a matter of declaring the function differently I wouldn't hesitate; but the fact that using an extension method requires it be coded in a different, static class makes me wonder if it's worth the effort or not. The example I'm using above is a fairly generic one and might have merit as an extension method that will be used in several places but often this is not the case and I would be coding the static class containing the extension in the same file as the single class that uses it.
I think the big advantage of extension methods is discoverability. If someone is unaware that one of their team members created a GetDescendents method in a utility class somewhere, they'll never use it. However, if that method starts to show up in Intellisense or in the Object Browser, there's a decent chance they will stumble across it. If you start to make more extensive use of extension methods, people will start to use the tools I mentioned to look for extensions that add value.
Most if not all extension methods fall into this category to some degree, since they can't operate on the internals of a class anymore than your static function. At any rate, any extension method can be rewritten in a static class with an extra parameter representing the object (arguably, that's exactly what an extension method is anyway).
To me, it's entirely a question of style: in the example you provided, I'd probably jump for the extension method. I think the important question here is, Is this function something I'd write as part of the class if I were to reimplement the class, and does it make sense as such? If yes, then go for it, if no, then consider a different solution.
An extension method only exists to improve readability - it is merely a syntax shortcut that allows you, by specifying the this keyword on the first argument, allows you to call the method on the object instance in question. So I think it is entirely reasonable.

Categories