2

In the Console class of the NET framework, Console.WriteLine() takes many different object types in as parameters. This is obvious when typing in Visual Studio and intellisense shows arrow keys with the different data types. Or in methods that take multiple parameters, you can see the intellisense description update depending on what object types are already entered

A screenshot to illustrate what I am trying to explain: screenshot

How do I write a method that can take a multiple types in?

4 Answers 4

9

It's called an overload, and you just create a method with the same name but different parameters:

/// <summary>
/// Writes a string followed by a newline to the console
/// </summary>
/// <param name="s">The value to write</param>
public void WriteLine(string s)
{
    //Do something with a string
}

/// <summary>
/// Writes the string representation of an object followed by a newline to the console
/// </summary>
/// <param name="o">The value to write</param>
public void WriteLine(object o)
{
    //Do something with an object
}

To get nice intellisense descriptions, you can add XML Documentation to each method.

Sign up to request clarification or add additional context in comments.

1 Comment

Add xml comments to get the nice intellisense descriptions
2

You can use method overloading.

You can define multiple methods with different input types, and use whichever one is appropriate for your uses.

For example:

public int AddTwoNumbers(int a, int b)
{
    return a + b;
}

public int AddTwoNumbers(double a, double b)
{
    return (int) a + b;
}

These both return an integer, but they take in different types and the code is different to handle the different types.

2 Comments

I think returning int from double+double method is not the best demonstration why method overloading is useful...
No, but it's a simple one that a beginner who doesn't even know what method overloading is would understand
1

this feature called method overloading in object oriented programming simply you create methods with diffrent signatures (type and number of parameters a function take)

for example:
public void Test(int a,int b)
{
 //do something
}

public void Test(int a,string b)
{
  //do something
}

you can read more about method overloading here : http://csharpindepth.com/Articles/General/Overloading.aspx

Comments

0

"WriteLine" method has a lot of differents parameters, it means overload, such as:

public static void HowLong(int x)
{
    //TODO: implement here
}

public static void HowLong(String x)
{
    //TODO: implement here
} 

static void Main(string[] args)
{
    HowLong(1);
    HowLong("1");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.