0

I tried to assign a value in aspx.cs file .

    static String cnn;
    cnn = "hi";

I get an error 'cnn is a field but used as a type'. I have added the code above all functions in the class.(not inside page load or any other event handler).

Why do I get this error and what is the reason ? How to fix ?

Srini Vas
  • 115
  • 1
  • 10

1 Answers1

3

You can't refer to cnn outside of a function, except when declaring the field.

If you want to declare and initialize the field, this can be done in one line:

static string cnn = "hi";

Note on style - in C#, use string, not String.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • It is still not working and I get the same error I mentioned ago – Srini Vas Jan 07 '13 at 17:16
  • @SriniVas - Is this happening on this line? Are you certain? It could very well be happening somewhere else where `cnn` is referenced. Where are you trying to use it? – Oded Jan 07 '13 at 17:17
  • That is only place where I used cnn. – Srini Vas Jan 07 '13 at 17:18
  • 2
    @SriniVas - since this is essentially identical to what Adil posted in [this answer](http://stackoverflow.com/a/14200741/1583), how come that answer worked and this one didn't? – Oded Jan 07 '13 at 17:19
  • I am not sure why it didn't. – Srini Vas Jan 07 '13 at 17:20
  • @Adil suggested "String" & Oded suggested "string" (that's the only difference I can see) – Csharp Jan 07 '13 at 17:28
  • @Csharp - When compiled, `string` becomes `System.String`, which is exactly what `String` is. It _cannot_ account for the different result. – Oded Jan 07 '13 at 17:36