How to create my own parameter method - c#

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;
}

Related

String format template as parameter

I'm beginer in C#. Now I have next task: In method I get template and arguments and I have to return formated string.
For example:
template = "Hello, {name}!"
name = "Bob"
So result must be a string -> Hello, Bob!
public static string GetHelloGreeting(string template, string name)
{
return string.Format(template, name);
}
String.Format expects an index in the braces. You want to pass the name in it, so you can replace it with the actual name value.
I'd suggest to use String.Replace:
public static string GetHelloGreeting(string template, string name)
{
return template.Replace("{name}", name);
}
You could provide a method which is more reusable. For example:
public static string ReplaceAll(string template, params (string key, string value)[] replacements)
{
foreach (var kv in replacements)
{
template = template.Replace("{"+ kv.key + "}", kv.value);
}
return template;
}
Your example:
string res = ReplaceAll("Hello, {name}!", ("name", "Bob"));
but also possible with multiple parameters:
string res = ReplaceAll("Hello, {name}! Now it's {time}", ("name", "Bob"), ("time", DateTime.Now.ToString("HH:mm")));
The value of your template parameter will have to change somehow. If you want to use string interpolation, this answer shows that. So
template = $"Hello, {name}"; in which case you wouldn't need to use String.Format at all. Just make sure you define name before you define template.
Or you could use String.Format(template, name); like you have but you would need template = "Hello, {0}!";
The 0 is the index of the variable that will go in that position. For more info see String.Format
when specifying a format you use an index for the parameters that will follow. It is called a composite format string:
string template = "Hello, {0}!"
this makes it independent of variable names. But the true reason is that the overload of the Format method that you are using takes a params array as parameter as you can see in the method signature:
public static string Format (string format, params object?[] args);
so the index that is found in the template will be applied to extract the objects on the appropriate places from the array of objects that you pass into the method
If you want to use string.Format(), the template must be correct. Add the character $ at the beginning of the template:
try this:
string name = "Bob";
string template = $"Hello, {name}!";
Console.WriteLine(GetHelloGreeting(template, name)); // Hello, Bob!
public static string GetHelloGreeting(string template, string name)
{
return string.Format(template, name);
}
reult:
Hello, Bob!

Unit test Case - MissingMethodException

This is method to Convert String[] To String.
private string ConvertStringArrayToString(System.String[] array)
{
string result = string.Join("<br />", array);
return result.ToString();
}
This is unit test case method for the above method.
[TestMethod]
public void ConvertStringArrayToString_shouldReturnString()
{
string returnedString = null;
PrivateObject o = new PrivateObject(typeof(DemoClass));
System.String[] array = new System.String[]
{
"Index0","Index0","Index0","Index0"
};
returnedString = (string)Convert.ChangeType((o.Invoke("ConvertStringArrayToString", array)), typeof(string));
}
This results in missing method exception.
I found the error is in Passing parameter i.e. string[]
But when I replace method access specifier as public, the test case works without error!
Please help why method cannot be able to access when it is private and string[].
I believe the problem is that array is being passed directly as the argument for the object[] parameter, whereas you really want it to be wrapped so it's just the first argument in an array of arguments. So I'd write this:
string[] array = { "Index0", "Index0", "Index0", "Index0" };
object[] args = { array };
var result = o.Invoke("ConvertStringArrayToString", args);
string returnedString = (string) result;
(There's no need to declare returnedString earlier, and you don't need to use Convert.ChangeType - a cast should be fine.)

Extension Methods. Error No overload for method 'WriteTextToConsole' takes 1 arguments

I'm learning C# and C and this C# code is giving me an error I don't understand. I'm reading about extension methods and this code is giving the error: No overload for method 'WriteTextToConsole' takes 1 arguments. As you can see, it takes exactly 1 arguments? I created the variables c and count only to be able to construct the string object. So I could try the extension in the String class. Is it right understood that the way you create an extension method: is to precede the parameter with the "this" keyword and the parameter is of the type of class to be extended?
The code is here:
Console.WriteLine();
M.WriteTextToConsole("Hello, world. Programming in C# is fun");
char c = 'A';
int count = 14;
String str = new String(c, count);
str.WriteTextToConsole("This is a string");
The method is here:
static class M
{
public static void WriteTextToConsole(this string text)
{
Console.WriteLine(text);
}
}
you need to call it as str.WriteTextToConsole();. In this case str would be passed as a single argument to M.WriteTextToConsole() method
When you call the extension method on the string the "this string text" parameter refers to the string itself,for example if it where "this Bitmap b" it would be an extension method for the bitmap and assuming you had created a bitmap object named bit the call would be bit.WriteTextToConsole().If you want to had other parameters you need to add those to to the method declaration and to make so it is an option for the caller make it with the params keyword like so:
static class M
{
public static void WriteTextToConsole(this string text,params string[] str)
{
if (str.Length > 0)
{
//do something with extra string or strings
//you can make params Object[] but for this
//example i choose string[]
Console.WriteLine(text);
return;
}
Console.WriteLine(text);
}
}
Just remenber the this keyword must be the first parameter,refering to the type you are extending.
In the case of having optional strings i left the code with the duplicate console.WriteLine(text) you can rewrite it if you in both cases want the string displayed in the console(just remove the return and console writeline above it).

How is String.Format method treated?

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.

C# string insertions confused with optional parameters

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

Categories