SubmarineX
SubmarineX

Reputation: 850

Need declare a field corresponding a property in c#?

What is the difference between

private string someText;

public string SomeText
{
    get;
    set;
}

and

public string SomeText
{
    get;
    set;
}

Upvotes: 0

Views: 121

Answers (4)

Evan Trimboli
Evan Trimboli

Reputation: 30092

The second is just syntactic sugar for:

private string someText;

public string SomeText
{
    get { return someText; }
    set { someText = value; }
}

The second automatically handles the variable creation etc for you behind the scenes. In your first example, the private variable someText is never read/modified, it's just a class level variable that does nothing.

The reason you might want to use the first is if you need to do something more complicated in the getter/setter. For example you might want to check if something is initialized in the getter. Or you might want to validate the value in the setter.

Upvotes: 1

wlz
wlz

Reputation: 623

I think maybe you want to know the difference between

public class Test1
{
    private string _text;
    public string Text
    {
        get { return _text; }
        set { _text = value; }
    }
}

and

 public class Test2
{
    public string Text
    {
        get;
        set;
    }
}

If you disassemble these two classes into CIL , you will find it's almost the same except in the second case , the field was a auto generated one .

First case:

.property instance string Text
{
    .get instance string Syner.Test1::get_Text()
    .set instance void Syner.Test1::set_Text(string)
}


.field private string _text

Second case:

 .property instance string Text
{
    .get instance string Syner.Test2::get_Text()
    .set instance void Syner.Test2::set_Text(string)
}


.field private string <Text>k__BackingField
{
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
}

Upvotes: 2

NDJ
NDJ

Reputation: 5194

You do realise that your question is comparing two equal things? (

public string SomeText
{
    get;
    set;
}

)

I'm thinking what your question really is - is what is the difference between

private string someText;

public string SomeText
{
    get
     {
       return someText;
     }

    set 
     {
      someText = value;
     }
}

and :

public string SomeText
{
    get;
    set;
}

To which the answer is, in the 2nd example the backing fields still exist but are created for you - and you have no influence over the setting/getting; whereas in the first example you can put other checks in to make sure it's a valid value being set, etc.

Upvotes: 2

Rhys Bevilaqua
Rhys Bevilaqua

Reputation: 2167

nothing at all, your private member is not being used.

The compiler will compile

public string SomeText
{
     get;
     set;
}

to the equivalent of

private string _someText;

public string SomeText
{
   get { return _someText; }
   set { _someText = value; }
}

Upvotes: 3

Related Questions