Reputation: 129
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:
How do I write a method that can take a multiple types in?
Upvotes: 2
Views: 1187
Reputation: 21887
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.
Upvotes: 9
Reputation: 382
"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");
}
Upvotes: 0
Reputation: 1942
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
Upvotes: 1
Reputation: 12375
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.
Upvotes: 2