1

Possible Duplicate:
What is a method group in C#?

What is the problem with the '+' signal to concatenate a string?

This is print screen of my problem:

http://pbrd.co/UtDf61

Json(new
{
    dom = "RegistroUsuario",
    type = "showErrorToast",
    msg = "Erro: " + e,
}, JsonRequestBehavior.AllowGet);

string jsScript = "closeAndRedirectJson(" + Json + ")";

The error I am receiving is

Operation '+' cannot be applied to operands of type 'string' and 'method group'

Community
  • 1
  • 1
Guilherme Longo
  • 2,278
  • 7
  • 44
  • 64
  • 2
    `Json` appears to be a function. A function is not a string. Also, we don’t want a link to a screenshot of your problem - please just include the code in your question and write out what the error is. – Ry- Dec 26 '12 at 19:43
  • 1
    Please try not to post a link to an image, but instead post your code inside of the question itself. – Dave Zych Dec 26 '12 at 19:46

3 Answers3

6

As the error is clearly telling you, Json is neither a string nor an object.

Rather, it's a method group – a "reference" to function.
Unlike Javascript, C# functions are not objects; you can only use a method group to create a delegate instance. (which isn't what you want anyway)

If you want to convert your earlier object to a usable string of JSON, you'll need to use the JavascriptSerializer class directly.

The Json() method returns a JsonResult instance which can only be used to write the JSON to the response body; it's useless here.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
3

Consider the following:

static string X() { return "hello"; }
static void Main()
{
    Console.WriteLine(X + "goodbye");
}

Do you see the problem? The code concatenates the method X with the string "goodbye". But a method is not something that can be concatenated to a string! The intention was to call the method. The correct code is:

    Console.WriteLine(X() + "goodbye");

It is not clear to me from your program fragment what you intend to concatenate in there, but Json is a method, not something that can be concatenated with a string.

Incidentally, the reason that the compiler is using the somewhat confusing term "method group" in the error is because you might be in this situation:

static string X(int y) { return "hello"; }
static string X(double z) { return "hello"; }
static void Main()
{
    Console.WriteLine(X + "goodbye");
}

Now it is unclear which method X is referring to, and in fact, the C# language says that the expression X refers to both methods. Such an expression is classified as a "method group". The process of overload resolution picks a unique best method out of a method group.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • It's actually worse than that; `Json()` returns neither a string nor an object with a usable `ToString()`. – SLaks Dec 26 '12 at 19:49
-6

It's a function. Not a string. You can't use it with concatenation.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364