Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a method like string.Format with intellisense support

Consider a method to write with a format parameter like string.Format's frist parameter. As you know the Intellisense is aware of first parameter's constraints and checks for its consistency with parameters. How can I write such method.

As a simple example, consider a wrap of string.Format like:

public string MyStringFomratter(string formatStr, params object[] arguments)
{
    // Do some checking and apply some logic
    return string.Format(formatStr, arguments);
}

How can I say to the compiler or IDE that formatStr is something like string.Format's first parameter?

So if I have some code like this:

var x = MyStringFormatter("FristName: {0}, LastName: {1}", firstName);
// This code should generate a warning in the IDE
like image 733
mehrandvd Avatar asked Jan 12 '14 11:01

mehrandvd


People also ask

How do you write in string format?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.

What is %s in string format?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string.

What is the name of the string format method?

The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.


1 Answers

You cannot make Visual Studio analyze parameter content for you - it simply verifies that code is compilable, and String.Format is compilable even if you haven't specified parameters for all placeholders. But you can use Visual Studio add-in (e.g. ReSharper or CodeRush) which analyzes placeholders count for String.Format formatting string and verifies parameters count passed to this method.

BTW I'm not using ReSharper but looks like it has support for marking any method as string formatting method - Defining Custom String Formatting Methods. You just should annotate your method with StringFormatMethodAttribute attribute:

[StringFormatMethod("formatStr")]
public string MyStringFomratter(string formatStr, params object[] arguments)
{
    // Do some checking and apply some logic
    return string.Format(formatStr, arguments);
}
like image 108
Sergey Berezovskiy Avatar answered Nov 15 '22 15:11

Sergey Berezovskiy