I have a method: relevant part below
void foo(various parameters)
{
tsk.run(various parameters);
}
Now the parameters with the tsk.run need to spaced as such:
tsk.run(param 1 + " " param2 + " " param3);, etc depending on how many parameters.
The parameters will form one continuous string that is used in a command line app.
At most, there will be 4 parameters, so is it best to do an overload method for each. Or is there a way using the Param keyword to take the parameters and add them to the tsk.run() method.
Would it be worth using param[] and then looping through, concatenating into a string and then put that into run?
You needn't loop:
void Foo(params string[] args)
{
tsk.run(String.Join(" ", args));
}
If you know the number of arguments use overload as it will be more efficient.
The compiler will be able to directly call the right method and you can assign default values.
If the paramlist is created dynamically and can vary more in length, use params.
Or in you example skip params and just use a string list or string array.
well you could do that by using
(params object[] parameters)
then inside method create a Strigbuilder and append each param from list to it in your required fashion.
Its unclear whether your parameters are all strings, or they are really various by type and object signature should be used. If parameters are different by type I think having params method with objects would create more problems than help.
If they are all strings I think params is ideal solution for this situation.
void foo( params string[ ] parameters )
{
StringBuilder sb = new StringBuilder( );
foreach ( string parameter in parameters )
{
sb.Append( parameter );
sb.Append( " " );
}
tsk.run( sb.ToString( ) );
}
Like this:
void foo<T>(params T[] parameters)
{
tsk.run(string.Join<T>(" ", parameters));
}
Related
I saw some code from a C# Console Application that can pass a string-valued parameter . My question is how can I create my own parametered method?
For example, the following code will pass the parameter value to {0} and print the string with value of Leonel.
Console.Write("{0}", "Leonel");
How can I make a method that can pass a parameter value to string format and return a parameterize string?
public string Combine(string format, params object[] args)
{
var parameterize = //("{0}", args) //I need something like this.
return parameterize;
}
I'm not totally clear on what you're asking, but would calling string.Format work?
string str = string.Format("The value is: {0}", val);
That should call the same underlying function as Console.Write does. It returns the string that would otherwise be printed to the Console. Given that, you probably don't even want your Combine method, as string.Format would take its place.
You can use the static method
string.Format(string str, params string[] formatters);
with your example:
public string Combine(string format, params object[] args)
{
var parameterize = string.Format(format, args);
return parameterize;
}
trying to understand!!
string myValue1 = "1";
string myValue2 = "2";
Console.WriteLine(myValue1, myValue2);
This only prints out the first value, if one use + the it concatenates them together. is there a way to have the two values printed on separate lines.
I can use two WriteLines (one for each Value) but I am trying to be more efficient (or Stupid)!!
Use Environment.NewLine for printing values on different lines. Use Console.WriteLine Method (String, Object[]) overload which takes a string format and values.
Console.WriteLine("{0}{1}{2}", myValue1, Environment.NewLine, myValue2);
If this is a single statement, than I really doubt if it will give you any performance gain.
You are using the format overload http://msdn.microsoft.com/en-us/library/828t9b9h(v=vs.110).aspx
This one supports placeholders {0}, {1}... The first argument is the format and the subsequent arguments are put in the placeholder. Because your string does not have any placeholders the second value is missing. For what you want to do you'd best just call WriteLine twice.
Console.WriteLine(myValue1);
Console.WriteLine(myValue2);
Concatenating new line will make your code harder to read. Don't try to be efficient this way. It is stupid :)
You can also use a verbatim string literal # and it will look like that:
Console.WriteLine(#"{0}
{1}", myValue1, myValue2);
The output will be on separate lines. However, in my opinion the c# doesn't look well written.
concat an Environment.NewLine //
If by efficient you mean write less code you can do this:
static void Main(string[] args)
{
WriteMultiLine(1,2, "hello", TimeSpan.FromMinutes(3));
Console.ReadLine();
}
public static void WriteMultiLine(params object[] values)
{
foreach (var value in values)
{
Console.WriteLine(value);
}
}
You can print whatever you want on different lines.
The output is:
1
2
hello
00:03:00
As is described at Microsoft Site ,String.Format arranges some String Variables into a single String and is another way how to concate string's in c#.
string.Format("Name = {0} Surname = {1}",name,surname);
My question is how does this work ?
Is this method a Special method ,and can i create a method similar to this one which accepts at every {n} only an Integer .
Or is this method interpreted in a different way by compiler ,if yes than how does the compiler accesses this method .
If it's possible i would like to see ,how does the compiler interpret this Method.
PS : How does it work ,when you can send as much parameters as you want to a method ?
[EDIT]
Does it mean ,that String.Format takes the first Parameter and filter's into with a Regex or Whatever tool (Split etc) to get where {Number} is and places there a String token from second params portion ?
Sending a variable number of parameters to a method is done like this:
public static string MyStringFormat(string formatString, params object [] args)
{
}
You can now pass as many parameters as you like to this:
MyStringFormat("{0}{1}",42,"Hello World")
MyStringFormat("{0}{1}{2}",42,"Hello World",999.9)
Within the method, these arguments are simply an array (of object in this case).
here are the docs on the params keyword.
As for writing you own method to accept numeric input like Format does, this would be one way (using regular expressions):
public static string MyStringFormat(string formatString, params object[] args)
{
var regex = new Regex("{([0-9]*)}");
return regex.Replace(formatString,m =>
{
int index = int.Parse(m.Groups[1].Value);
if(index<args.Length)
return args[index].ToString();
return String.Empty;
});
}
Live example: http://rextester.com/rundotnet?code=OMZC13551
It is a normal function.
It parses the string and calls ToString on the incoming parameters (if needed) in order to construct the new string.
The signature of the overload you have in your example is:
public static string Format(
string format,
params Object[] args
)
There is nothing to stop you from creating your own (though I would probably just delegate to the built in string.Format).
Use params: http://msdn.microsoft.com/en-us/library/w5zay9db.aspx
there is no magic there Cody, look at this method:
public static void UseParams(params int[] list)
{
for (int i = 0 ; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine();
}
you can call it passing as many int you like, it's the params parameter type :)
Edit:
params is very useful it allows us, for example, to pass to our logging wrapper all method's parameters values in a dynamic way without knowing how many of them each method has, the logger will then dump all those values one by one using Reflection to find out the parameter name as well.
The braces in the string are placeholders and a number within that denotes the index of argument it is to be replaced with.
Format is of type (string format, params object[] args) and it is the index in this object[] which is helpful.
(I think it internally uses the StringBuilder.AppendFormat) for substituting those values)
The signature of String.Format looks like this:
public static string Format (string format, params Object[] args)
Note the second parameter, marked with the params keyword. That one provides the functionality to add multiple parameters when calling the function. Inside the function you can access the parameters by index or iterating over args array:
public static string Format (string format, params Object[] args)
{
foreach (Object o in args)
Console.WriteLine(o);
}
Have a look at the C# Reference.
Where can I get info about implementing my own methods that have the ellipsis notation,
e.g.
static void my_printf(char* format, ...) { }
Also is that called ellipsis notation or is there a fancier name?
Have a look at the params keyword
From https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params:
By using the params keyword, you can specify a method parameter that
takes a variable number of arguments.
You can send a comma-separated list of arguments of the type specified
in the parameter declaration or an array of arguments of the specified
type. You also can send no arguments. If you send no arguments, the
length of the params list is zero.
static void MyPrintf(string format, params object[] args) { }
...
MyPrintf(1, 'a', "test");
I'm fairly new to C#, and trying to figure out string insertions (i.e. "some {0} string", toInsert), and ran across a problem I wasn't expecting...
In the case where you have two constructors:
public MyClass(String arg1) { ... }
public MyClass(String arg1, String arg2) { ... }
Is it possible for me to use the first constructor with a string insertion?
...
toInsert = "def"
myClass = new MyClass("abc{0}ghi", toInsert)
...
Or will C# interpret this as the second constructor and pass a literal "abc{0}ghi" as the first argument?
Yes, this will be interpreted as just a second parameter.
The behavior you describe is called string formatting and everything that accepts strings in this style uses string.Format() in the background. See the documentation of that method for details.
To get the desired behavior, use this code:
myClass = new MyClass(string.Format("abc{0}ghi", toInsert));
Just do:
public MyClass(string format, params object[] args)
{
this.FormattedValue = string.Format(format, args);
}
Or will C# interpret this as the
second constructor and pass a literal
"abc{0}ghi" as the first argument?
This is the right answer.
I think If you use String.Format("abc{0}ghi", toInsert) then it will take the first constructor