Tutorial :C#, Is it possible to avoid defining private fields and still use set/get on public fields?


Like this:

public String text {get; set{      // here comes some setter checking / setter logic      // finally assign the value to the var without using the setter      <is_there_a_"without_setter"_keyword?> text = value;    }  }  


No there is not a way to do that


No. The property is the exposed interface (not a C# interface) for controlling access to the private backing field. The special syntax introduced in C# 3 is what's called "syntactic sugar" - the compiler actually turns this into a private field that you never see with a get/set property to access it.

Edit: Properties themselves don't store data. They simply control access to data stored elsewhere, where one common case is in a private field.

Another Edit: This is the sugar syntax I'm referring to:

// When this is compiled, it actually creates a private   // field for you, which the property accesses.  public int MyProperty  {      get;      set;  }  


If you define custom code for your setter, however simple, then you must also define the get method if you want it

The farther you can go without writing this custom code is

public String text {get; protected set}  

which allows public read access and modifiction only in your classes and its descendant


There is no way to do that when you have custom logic to apply. If you have a simple property, you can do:

public int Foo { get; set; }  

You can also set the visibilities of each:

public int Foo { get; private set; }  


You cannot do that for an property where you do not define the backing field. When you define such a property, the C# compiler generates a private field with the name <PropertyName>k_BackingField in the MSIL. As other posters have pointed out, at most you can tweak the access modifiers on the property.

There are some rules regarding that too, which are mostly common sense:

  • Access control on get and set can only be more restrictive than on the property. i.e. You cannot have a private PropertyName and give it a public get or set.
  • You cannot definite both get and set to be private when the property is public. At most one attribute can be private.

However, this is all syntatic sugar provided by the C# compiler. You could provide the backing field yourself, and provide your get and set implementations for the property. You could choose to make the backing field public.

There is only a minor difference in the MSIL code generated for both cases ( The generated backing field includes an System.Runtime.CompilerServices.CompilerGeneratedAttribute attribute. So too do the generated get and set methods )

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »