Compile error using C# automatically implemented properties - c#

A C# Noob, I am trying to use SharpDevelop utility to convert my VB.NET application a C#.
I am noticing that my automatically implemented properties are generating a lot of errors. For example, take the following property:
public SqlDateTime DateOfBirth { get; set; }
Whenever I try to access the implied underlying module level variable, _DateOfBirth, I get the error.
Error 699 The name '_DateOfBirth' does not exist in the current context D:\Users\Chad\Desktop\BESI CSharp\BESI\BESI.BusinessObjects.ConvertedToC#\ChinaVisa.cs 240 13 Besi.BusinessObjects.Converted
I could expand the properties declarations out to full-fledged properties, but this should n't be necessary and I'd like to understand why I am getting this error.

You cannot access the compiler-created backing variable - you must use the property. The compiler-generated backing field is specifically named in such a way to prevent you from accessing it (it is not named _DateOfBirth, it is named something like <DateOfBirth>k__BackingField).
Access the property directly - if you need to manipulate the backing field directly then don't use an automatically implemented property.
Just a side note - it doesn't matter what the property name is (it is an implementation detail and could change on different versions of the compiler or with different compiler implementations altogether). The field is given an identifier that is specifically designed to meet the naming restrictions of the CLR but fail the naming restrictions of C# making it impossible to ever write straight C# code that accesses that variable directly.
Also remember that automatically implemented properties are not public fields. They are a shorthand that the compiler expands for you (sort of like a macro).
So this class:
class Bar
{
public object Foo { get; set; }
}
Gets expanded to this:
class Bar
{
[CompilerGenerated]
private object <Foo>k__BackingField;
public object Foo
{
[CompilerGenerated]
get
{
return this.<Foo>k__BackingField;
}
[CompilerGenerated]
set
{
this.<Foo>k__BackingField = value;
}
}
}
It is still a full property - you are simply allowing the compiler to write the getters and setters for you.

If you use automatically generated properties, you cannot rely on the compiler picking any specific name for the backing field. That's entirely compiler-specific, and even if you could access those fields, your code might still break if you use another compiler.

Related

Difference between "public bool xy" and "public bool xy { get; set; } [duplicate]

I failed to understand why auto implemented property language feature exist in C# 3.0.
What the difference it is making when you say
public string FirstName;
than
public string FirstName { get; set; }
Because they are implemented differently in the resulting IL code (and machine language). An Automatic property is still exposed as a public getter and setter, whereas a public field is just that - a single field..
Thus, implementing an auto property allows you at some later date to change the internal behavior of either the getter or setter (like adding a validator) without recompiling or re=coding any dependant classes that use it...
Just to add to what other people have said, declaring a public field, the field is accessible for read and write. declaring public automatic property, although the property is public, you can still add modifier to control the accessibility at the get/set level.
public string FirstName { get; private set; }
The user of your class sees FirstName as public property. However, he/she cannot write to it.
Consider what happens if you later want to change each of them to a property with a custom implementation. If it's an automatically implemented property, you just add a field and change the implementation. Full source and binary compatibility.
If it's a field to start with, you get neither source nor binary compatibility. You have to rebuild everything that references it, and fix up anything which no longer compiles.
Additionally, properties have various benefits over fields. My main personal objection to fields is that it exposes an implementation decision in the API.
The difference is that other assemblies compiled with code that read the property is compiled against a property.
If you later on decide you need to add code to the getter or setter, you can do that, without having to force every other assembly linked to it to recompile.
Not so with fields. If you later on change a field to be a property, in order to add that code, other assemblies linked against yours will cease to function properly since they're compiled to read a field, not a property.
Also, lots of code is written to find properties, not fields, like data binding and similar.
because of this use:
public string FirstName { get; private set; }
easy property, that 'kosher' by OO rules
The first is a public field, while the second is a public property.
The main difference is in how they are used. For example WPF can only data bind to properties, not fields.
Auto properties are Compiler generated regular properties, they use a backing fields like any regular property but you don't need to write the code for that. Here is a very illustrative sample (thanks to Reflector) of the code generated by the compiler:
[CompilerGenerated]
private string <ContentType>k__BackingField;
public string ContentType
{
[CompilerGenerated]
get
{
return this.<ContentType>k__BackingField;
}
[CompilerGenerated]
set
{
this.<ContentType>k__BackingField = value;
}
}

What is the difference between a property and a variable

I have a confusion about understanding Property and Variables
public class ABC()
{
public int A;
public int B { get; set; }
}
What is the exact difference between in A and B?
As many have pointed out, A is a field, B is a property.
The real question is, why should you care, and what to use?
I refer to a blog post of Jonathan Aneja:
(Its in VB, but it applies to C# as well ;))
So why use properties over fields, 5 reasons:
1. Fields can’t be used in Interfaces
You can’t enforce the existence of a
field in an object’s public contract
through an interface. For properties
though it works fine.
2. Validation
While your application currently may
not require any validation logic to
set a particular value, changing
business requirements may require
inserting this logic later. At that
point changing a field to a property
is a breaking change for consumers of
your API. (For example if someone was
inspecting your class via reflection).
3. Binary Serialization
Changing a field to a property is a
breaking change if you’re using binary
serialization. Incidentally, this is
one of the reasons VB10’s
auto-implemented properties have a
“bindable” backing field (i.e. you can
express the name of the backing field
in code) – that way, if you change an
auto-implemented property to an
expanded property, you can still
maintain serialization compatibility
by keeping the backing field name the
same (in C# you’re forced to change it
because it generates backing fields
with unbindable names).
4. A lot of the .NET databinding infrastructure binds to properties but not fields
I’ve heard arguments on both sides as
to whether or not that’s a good thing,
but the reality is that’s the way it
works right now. (Note from me: WPF bindings work on properties)
5. Exposing a public field is an FxCop violation
For many of the reasons listed above
:)
There might be more reasons.
I would also like to point to a blog post of Jeff Atwood and conclude with a quote from it:
The really important thing to take away here is to avoid writing code that doesn't matter. And property wrappers around public variables are the very essence of meaningless code.
A is a field, B is a property. A property is basically syntactic sugar for getters and setters. The class you have defined will be compiled into something like this:
public class ABC()
{
public int A;
private int backing_B;
public void set_B(int value)
{
backing_B = value;
}
public int get_B()
{
return backing_B;
}
}
Note that this kind of conversion is true for all C# properties -- accesses to ABC.B will be converted to method calls. Properties basically provide the illusion of a "variable" while actually just being a cleverly disguised pair of methods.
This is important, because it allows you to declare your own get and set method body, which can validate values or do other interesting things:
private int b;
public int B {
get { return b; }
set {
if (value < 0) throw new ArgumentOutOfRangeException("value");
b = value;
}
}
Note that most properties will use a field to store their value. Properties seldom exist on their own, apart from fields.
In C# any "variable" that has a getter and setter is referred to as a property. A variable has no getters and setters or so that is what the text books say.
My programming instructor made us have getters and setters for almost every variable that we created in Java. Even indexing variables he made us use a getter and setter if they were declared at the global class scope. I think this might have been overkill but it did get me to make getters and setters.
The real things about getters and setters are that they more than likely do more than just set an internal variable. Most setters are going to perform some type of data validation to make certain that data can be set to the variable. A getter might also check returning data for some criteria.
If your property is private and your setters and getters are public technically anyone could access your variable and change it as if they had public access to the actual variable. So, in reality, you should check your data to make certain that it is valid or some other data check.
private int myVariable;
public int myVariable
{
get
{
return myVariable;
}
set
{
if (value < 0)
{
throw new Exception("This is your exception some where else in code");
}
myVariable = value; //remember value is something that is
//declared automatically
}
}
public string FirstName { get; set; }
The above is a shorthand way of writing the following
private string firstName;
public string FirstName
{
get
{
//...code here
}
set
{
//...code here
}
}
A property is sort of a short getter and or setter. You can add logic to the set or get of the property or make them private which means that they are not accessible from the out side, where a variable is always accessible (if it is public).
Variable is, well, a variable.
Property is a special type of method that exposes that variable. And since it is a method, therefore, you can do some other things in it apart from just exposing the variable.
From MSDN:
The Property statement introduces the declaration of a property. A property can have a Get procedure (read only), a Set procedure (write only), or both (read-write). You can omit the Get and Set procedure when using an auto-implemented property. For more information, see Auto-Implemented Properties (Visual Basic).
You can use Property only at class level. This means the declaration context for a property must be a class, structure, module, or interface, and cannot be a source file, namespace, procedure, or block. For more information, see Declaration Contexts and Default Access Levels.
By default, properties use public access. You can adjust a property's access level with an access modifier on the Property statement, and you can optionally adjust one of its property procedures to a more restrictive access level.
There is a very good article (link below) about using fields/variables vs Properties from Microsoft itself. Though the article essentially talks about a FxCop violation rule, it clearly defines the difference between the two and the exact usage guidelines.
An excerpt from the article:
The primary use of a field should be as an implementation detail.
Fields should be private or internal and should be exposed by using
properties. Accessing a property is as easy as accessing a field, and
the code in a property's accessors can change as the type's features
expand without introducing breaking changes.
Refer:
https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-3.0/ms182141(v=vs.80)
In your example A is a public field on the class ABC and B is a public property on the class ABC. Specifically, B is an auto-implemented property. What this means is that "under the hood" the compiler does some of the work for you and effectively transforms your code into:
public class ABC()
{
private int b;
public int A;
public int B
{
get
{
return b;
}
set
{
b = value;
}
}
}
Variable is defined basically for accessing value from a class or into the same class according to their modifier assigned to those variable.
When we define a property there two methods created for single property so extra overhead is generated that is the drawback of property.
The advantages of properties is to get or set value into private variable of class.

Why use private members then use public properties to set them?

Seen a few examples of code where this happens:
public class Foo
{
string[] m_workID;
public string[] WorkID
{
get
{
return m_workID;
}
private set
{
m_workID = value;
}
}
}
What's the point of this?
Since the use m_workID unnescessary.
In general, the point is to separate implementation (the field) from API (the property).
Later on you can, should you wish, put logic, logging etc in the property without breaking either source or binary compatibility - but more importantly you're saying what your type is willing to do, rather than how it's going to do it.
I have an article giving more benefits of using properties instead of public fields.
In C# 3 you can make all of this a lot simpler with automatically implemented properties:
public class Foo
{
public string[] WorkID { get; private set; }
}
At that point you still have a public getter and a private setter, but the backing field (and property implementation) is generated for you behind the scenes. At any point you can change this to a "normal" fully-implemented property with a backing field, and you'll still have binary and source compatibility. (Compatibility of serialized objects is a different matter, mind you.)
Additionally, in this case you can't mirror the behaviour you want (the ability to read the value publicly but write it privately) with a field - you could have a readonly field, but then you could only write to it within the constructor. Personally I wish there were a similar shorthand for this:
public class Foo
{
private readonly int id;
public int Id { get { return id; } }
...
}
as I like immutable types, but that's a different matter.
In another different matter, it's generally not a good idea to expose arrays like this anyway - even though callers can't change which array WorkID refers to, they can change the contents of the array, which is probably not what you want.
In the example you've given you could get away without the property setter, just setting the field directly within the same class, but it would mean that if you ever wanted to add logging etc you'd have to find all those writes.
A property by itself doesn't provide anywhere to put the data - you need the field (m_workID) for storage, but it entirely correct to hide that behind a property for many, many reasons. In C# 3.0 you can reduce this to:
public string[] WorkID {get; private set;}
Which will do much of the same. Note that exposing an array itself may be problematic, as there is no mechanism for protecting data in an array - at least with an IList<string> you could (if needed) add extra code to sanity check things, or could make it immutable. I'm not saying this needs fixing, but it is something to watch.
In addition to the Object Oriented philosophy of data encapsulation, it helps when you need to do something every time your property is read/write.
You can have to perform a log, a validation, or any another method call later in your development.
If your property is public, you'll have to look around all your code to find and modify your code. And what if your code is used as a library by someone else ?
If your property is private with appropriate get/set methods, then you change the get/set and that's all.
You can use C# 3.0 auto properties feature to save time typing:
public class Foo
{
public string[] WorkID
{
get; private set;
}
}
In addition properties gives you lot of advantages in comparison to fields:
properties can be virtual
properties hide implementation details (not all properties are just trivial variable accessors)
properties can contain validation and logging code and raise change events
interfaces cannot contains fields but properties
A lot of times you only want to provide read access to a field. By using a property you can provide this access. As you mention you may want to perform operations before the field is accessed (lazy loading, e.g.). You have a lot of code in there that just isn't necessary anymore unless you're still working in .Net 2.0-.

C# Automatic Properties

I'm a bit confused on the point of Automatic properties in C# e.g
public string Forename{ get; set; }
I get that you are saving code by not having to declare a private variable, but what's the point of a property when you are not using any get or set logic? Why not just use
public string Forename;
I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?
Properties can have code put into them without breaking contract, fields can't have code put into them without changing them to properties (and breaking the interface). Properties can be read only or write only, fields can't. Properties can be data bound, fields can't.
You can write
public string Forename{ get; private set; }
to get read-only properties... Still not nearly as versatile as real properties, but it's a compromise that for some works.
I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?
In the first case, the compiler will automatically add a field for you, and wrap the property. It's basically the equivalent to doing:
private string forename;
public string Forename
{
get
{
return this.forename;
}
set
{
this.forename = value;
}
}
There are many advantages to using properties over fields. Even if you don't need some of the specific reasons, such as databinding, this helps to future-proof your API.
The main problem is that, if you make a field, but in v2 of your application, need a property, you'll break the API. By using an automatic property up front, you have the potential to change your API at any time, with no worry about source or binary compatibility issues.
It is meant that you expect to add the logic later.
If you do so and have it as property from the beginning, you will not have to rebuild the dependent code. If you change it from a variable to a property, then you will have to.
Consider looking at some related threads about Difference Between Automatic Properties and Public Fields, Fields vs Properties, Automatic Properties - Useful or Not?, Why Not to Use Public Fields.
Public data members are evil (in that the object doesn't control modification of it's own state - It becomes a global variable). Breaks encapsulation - a tenet of OOP.
Automatic properties are there to provide encapsulation and avoid drudgery of writing boiler plate code for simple properties.
public string ID { get; set;}
You can change automatic properties to non-automatic properties in the future (e.g. you have some validation in a setter for example)... and not break existing clients.
string m_ID;
public string ID
{
get { return m_ID; }
set
{
//validate value conforms to a certain pattern via a regex match
m_ID = value;
}
}
You cannot do the same with public data attributes. Changing a data attribute to a property will force existing clients to recompile before they can interact again.
When adding auto properties the compiler will add get set logic into the application, this means that if you later add to this logic, and references to your property from external libraries will still work.
If you migrated from a public variable to a property, this would be a breaking change for other libraries that reference yours - hence, why not start with an auto property? :)
For one, you can set the property to virtual and implement logic in an inheriting class.
You can also implement logic in the same class afterwards and there won't be side-effects on any code relying on the class.
Not all properties need get/set logic. If they do, you use a private variable.
For example, in a MV-something pattern, your model would not have much logic. But you can mix and match as needed.
If you were to use a field like you suggested in place of a property, you can't for example define an interface to describe your class correctly, since interfaces cannot contain data fields.
A property is like a contract, and you can change the implemenation of a property without affecting the clients using your classes and properties. You may not have any logic today, but as business requirements change and if you want to introduce any code, properties are your safest bet. The following 2 links are excellent c# video tutorials. The first one explains the need of properties over just using fields and the second video explains different types of properties. I found them very useful.
Need for the Properties in C#
Poperties in C#, Read Only, Write Only, Read/Write, Auto Implemented
Take a look at the following code and explanation.
The most common implementation for a property is getter or a setter that simply reads and writes to a private field of the same type as a property. An automatic property declaration instructs the compiler to provide this implementation. The compiler automatically generates a private backing field.
Look into the following code:-
public class Stock
{
decimal currentPrice ; // private backing field.
public decimal CurrentPrice
{
get { return currentPrice ; }
set { currentPrice = value ; }
}
}
The same code can be rewritten as :-
public class Stock
{
public decimal CurrentPrice { get ; set ; } // The compiler will auto generate a backing field.
}
SOURCE:- C# in a Nutshell

Difference between Automatic Properties and public field in C# 3.0

I failed to understand why auto implemented property language feature exist in C# 3.0.
What the difference it is making when you say
public string FirstName;
than
public string FirstName { get; set; }
Because they are implemented differently in the resulting IL code (and machine language). An Automatic property is still exposed as a public getter and setter, whereas a public field is just that - a single field..
Thus, implementing an auto property allows you at some later date to change the internal behavior of either the getter or setter (like adding a validator) without recompiling or re=coding any dependant classes that use it...
Just to add to what other people have said, declaring a public field, the field is accessible for read and write. declaring public automatic property, although the property is public, you can still add modifier to control the accessibility at the get/set level.
public string FirstName { get; private set; }
The user of your class sees FirstName as public property. However, he/she cannot write to it.
Consider what happens if you later want to change each of them to a property with a custom implementation. If it's an automatically implemented property, you just add a field and change the implementation. Full source and binary compatibility.
If it's a field to start with, you get neither source nor binary compatibility. You have to rebuild everything that references it, and fix up anything which no longer compiles.
Additionally, properties have various benefits over fields. My main personal objection to fields is that it exposes an implementation decision in the API.
The difference is that other assemblies compiled with code that read the property is compiled against a property.
If you later on decide you need to add code to the getter or setter, you can do that, without having to force every other assembly linked to it to recompile.
Not so with fields. If you later on change a field to be a property, in order to add that code, other assemblies linked against yours will cease to function properly since they're compiled to read a field, not a property.
Also, lots of code is written to find properties, not fields, like data binding and similar.
because of this use:
public string FirstName { get; private set; }
easy property, that 'kosher' by OO rules
The first is a public field, while the second is a public property.
The main difference is in how they are used. For example WPF can only data bind to properties, not fields.
Auto properties are Compiler generated regular properties, they use a backing fields like any regular property but you don't need to write the code for that. Here is a very illustrative sample (thanks to Reflector) of the code generated by the compiler:
[CompilerGenerated]
private string <ContentType>k__BackingField;
public string ContentType
{
[CompilerGenerated]
get
{
return this.<ContentType>k__BackingField;
}
[CompilerGenerated]
set
{
this.<ContentType>k__BackingField = value;
}
}

Categories