简体   繁体   中英

Proper Variable Declaration in C#

I noticed some people declare a private variable and then a public variable with the get and set statements:

private string myvariable = string.Empty;
public string MyVariable
{
    get { return myvariable; }
    set { myvariable = value ?? string.Empty; }
}

and then some people just do the following:

public string MyVariable
{
    get { return value; }
    set { MyVariable = value; }
}

Being a bear of little intelligence (yes, I have kids... why do you ask?) I can't figure out why you would choose one over the other. Isn't it just as effective in using a public variable that you can set any time using the set method of the variable?

Can anyone shed some light on this for me?

UPDATE: I corrected the second example after several people pointed out it wouldn't compile. Sorry about that, but the question still remains...

Your second example won't compile, as the getter's value variable doesn't exist. Also, the setter would result in the eponymous StackOverflow exception!

In C# 3.0, you can use the following syntax to have the compiler create the private backing variable:

public string MyVariable { get; set; }

This wouldn't give you the extra null checking your first example has, though. You'd probably have to stick with your first example's method if you need custom logic in the setter.

As others have mentioned, your second example doesn't compile.

However, there are very good reasons for not using a public field. In fact, your example demonstrates one of them - for this property, even if you set it to null, you'll get back an empty string if you ask for it again. Whether that's appropriate or not for that property (it's slightly odd) depends on the exact use - but it's not the behaviour of a public field.

I've got a whole article about why properties are better than public fields which you may find useful.

This is a very interesting read on this topic. However, I am pretty sure I have read somewhere on MSDN that objects with public variables are lighter than having properties (can't find the link).

Having a trivial getter and setter is very similar to using a public field.

The main argument for preferring getters and setters over properties used to be the uniform access principle , but since C# has properties is easy to replace a public field with a property and recompile.

It's not perfect (see Jon Skeet's article), but the arguments against using public fields aren't so strong that it makes it "evil", as long as you're aware of the difference.

Personally, I like being able to easily specify a default value for a public field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM