c# parameters question - c#

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.

Related

C#: Anonymous method vs Named method

I'm new to SO and programming and learning day by day with bits and pieces of tech (C#) jargons.
After Googling for a while, below is what I've researched about methods
A Method is a block of statements, which serves for code reusability
& it also supports overloading with different SIGNATURE....for ex:
drawShape(2pts), drawShape(3pts) etc...
An Anonymous method is one with block of statements, but no
name....(as its premature to ask, in wt situation we come across
anonymous method...any articles, samples ...)
Named method: Here's a link but at the end i didn't get what Named Method actually is...
Can anyone explain what a "Named" method is, and where do we use anonymous method?
A named method is a method you can call by its name (e.g. it is a function that has a name). For example, you have defined a function to add two numbers:
int f(int x, int y)
{
return x+y;
}
You would call this method by its name like so: f(1, 2);.
Anonymous method is a method that is passed as an argument to a function without the need for its name. These methods can be constructed at runtime or evaluated from a lambda expression at compile time.
These methods are often used in LINQ queries, for example:
int maxSmallerThan10 = array.Where(x => x < 10).Max();
The expression x => x < 10 is called a lambda expression and its result is an anonymous function that will be run by the method Where.
If you are a beginner, I would suggest you first read about more basic stuff. Check out the following links:
http://www.completecsharptutorial.com/
http://www.csharp-station.com/tutorial.aspx
http://www.homeandlearn.co.uk/csharp/csharp.html
Let's start from a simple method.
void MyMethod()
{
Console.WriteLine("Inside MyMethod"); //Write to output
}
The above method is a named-method which just writes Inside MyMethod to the output window.
Anonymous methods are some methods used in some special scenarios (when using delegates) where the method definition is usually smaller where you don't specify the name of the method.
For example, (delegate) => { Console.WriteLine("Inside Mymethod");}
Just start writing some simple programs and in the due course, when you use delegates or some advanced concepts, you will yourself learn. :)
Explanation by Analogy
Normally when we tell stories we refer to people by name:
"Freddie"
"Who's Freddie?"
"You know, Freddie, Freddie from Sales - the male guy with the red hair, who burned the building down...?"
In reality nobody cares who the person is, department he works etc. it's not like we'll refer to him every again. We want to be able to say: "Some guy burned down our building". All the other stuff (hair color, name etc.) is irrelevant and/or can be inferred.
What does this have to do with c#?
Typically in c# you would have to define a method if you want to use it: you must tell the compiler (typically):
what it is called,
and what goes into it (parameters + their types),
as well as what should come out (return type),
and whether it is something you can do in the privacy of your home or whether you can do it in public. (scope)
When you do that with methods, you are basically using named methods. But writing them out: that's a lot of effort. Especially if all of that can be inferred and you're never going to use it again.
That's basically where anonymous methods come in. It's like a disposable method - something quick and dirty - it reduces the amount you have to type in. That's basically the purpose of them.
Anonymous methods or anonymous functions, what seems to be the same, basically are delegates. As the link you point out: http://msdn.microsoft.com/en-us/library/bb882516.aspx describes, anonymous methods provide a simplified way to pass method to be executed by another method. Like a callback.
Another way to see it, is think about lambda expressions.
A named by the contrast is any common method.
From MSDN:
A delegate can be associated with a named method. When you instantiate a delegate by using a named method, the method is passed as a parameter. This is called using a named method. Delegates constructed with a named method can encapsulate either a static method or an instance method. Named methods are the only way to instantiate a delegate in earlier versions of C#. However, in a situation where creating a new method is unwanted overhead, C# enables you to instantiate a delegate and immediately specify a code block that the delegate will process when it is called. The block can contain either a lambda expression or an anonymous method.
and
In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code. However, the information about anonymous methods in this topic also applies to lambda expressions. There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions. For more information specifically about lambda expressions, see Lambda Expressions (C# Programming Guide). Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.
So in answer to your question about when to use anonymous methods, then MSDN says: in a situation where creating a new method is unwanted overhead.
In my experience it's more down to a question of code reuse and readability.
Links:
http://msdn.microsoft.com/en-us/library/98dc08ac.aspx
http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx
Hope that helps

Why does javascript have functions whereas C# has methods?

Why are they termed differently?
Isn't the nature/purpose/place of a function identical to that of a method?
Functions stand alone and methods are members of a class. That's all. (it's really all the same.)
A method is a function that is attached to an object.
JavaScript functions are usually referred to as methods when used in the context of an object.
e.g. document.getElementById('foo') uses the getElementById method.
Function is a very old term meaning a segment of code that accomplishes some task (does some function, if you will).
Method is a relatively newer term (came with OO programming) that means a function that belongs to a specific instance of an object.
All methods are functions, but not all functions are methods.
See this related question from the programmers stackexchange.
You usually find the term function when dealing with procedural code. OOP uses the term method but they are the same thing.
A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value).
All data that is passed to a function is explicitly passed.
A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences.
It is implicitly passed the object for which it was called
It is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data)
Also, another answer: Difference between function and method?
Well, its all about the names, but generally functions and methods are the same thing, and of course have the same purpose.
It all began with the first programming languages, where they where called functions, but as more higher level programming languages arose, i guess they thought to name them methods even if they are and serve the sasme purpose.
EDIT:
Functions are not part of any object or class.
Methods are a memeber of an object or class.

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.

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.

How Do I Handle Conflicts in Overloaded Method Signatures?

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

Categories