Gobind
Gobind

Reputation: 598

Can we declare a property inside a method in c#?

We can declare a local variable inside a method. But why can't we declare a property or field in side a method?

In the below example I can able to declare a local variable inside a method but can't able to declare a property.

I am new to c#. So please correct me if I am wrong.

class Program
    {
        Public void Learn()
        {
           int f = 5;
          // int a { get; set;};
        }
    }

Upvotes: 0

Views: 1258

Answers (1)

Sweeper
Sweeper

Reputation: 274035

I can able to declare a field inside a static method

What you have declared is not a field, but a local variable. Fields don't exist in methods.

The reason for this is because fields and properties represent the state of an object. A MusicPlayer object may have things like IsPlaying, Volume as its properties. Those are the object's "state". The states belong to the object, not one particular method of that object, like StartPlaying().

Local variables' purpose is to temporarily store some value to help the method do its job. They are kind of like pieces of scrap paper. You might have a method called SolveQuadratic(double a, double b, double c) and you might have a local variable called discriminent that stores b * b - 4 * a * c, so that you don't have to rewrite the expression b * b - 4 * a * c every time.

This is why you can't have properties inside methods, static or otherwise. They don't belong there.

Upvotes: 1

Related Questions