0

Why we can not apply readonly key word on method scope.but const is working fine.

public void show(){
   const string test = "test";      
}
public void show(){
   readonly string test="test";
}

any help would be appreciated.

atul bisht
  • 31
  • 5

1 Answers1

0

readonly cannot be used in that context. It can only be used when declaring fields inside class/struct.

The readonly keyword is a modifier that you can use on fields.

You use the const keyword to declare a constant field or a constant local.

Therefore your code doesn't even compile and doesn't make sense. To see difference between readonly and const when declaring fields see What is the difference between const and readonly?.

Update

To see why C# does not allow readonly local variables see Why does C# disallow readonly local variables?

Community
  • 1
  • 1
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263