Strange line in C# camera code - c#

My team is working on documentation for a robot project. We're currently documenting some camera code but we don't understand some lines.
public Mat Image { get; set; }
public double GyroAngle { get; set; }
Could anyone explain what these lines are doing? If the GyroAngle is simply a double why does it have { get; set; }? Thanks in advance.

It is not strange at all.
A field cannot be used in interfaces but properties can.
Most .NET binding can be done against a property. Not fields
You can change the implementation of a property and keep the contract so no dependent code breaks. For example, in the setter you may add validation. You may not have validation today, but if you do in the future, you can add that. If it was a field, and you change it to property, many bad things will happen such as binary serialization may break.
Some tools will also yell at you if you expose a field as public.

The MSDN has some useful info.
public string FirstName { get; set; } = "Jane";
The class that is shown in the previous example is mutable. Client code can change the values in objects after they are created. In complex classes that contain significant behavior (methods) as well as data, it is often necessary to have public properties. However, for small classes or structs that just encapsulate a set of values (data) and have little or no behaviors, you should either make the objects immutable by declaring the set accessor as private (immutable to consumers) or by declaring only a get accessor (immutable everywhere except the constructor). For more information, see How to: Implement a Lightweight Class with Auto-Implemented Properties.

Related

Why is it desirable to use all properties instead of public instance variables in c#?

I know properties have some advantages, but if you think you won't need a property, what's the harm in making it a public instance?
People say that changing the public field to a property will break code if you try to do it later on but in my experience changing it to a property breaks nothing.
I think that people mean that it breaks ABI (binary) compatibility, not the API (source) compatibility.
Although the syntax is identical, behind the scenes, access to properties and access to member variables are compiled differently.
That said, if your variable/property is not to be used from an assembly that you yourself do not compile, then there is no harm in changing it. But if it is part of a public interface, then it is better to make it a property, so that you will not regret it in the future.
It's about maintaining both binary and source compatibility. Some time in the future you may decide to make logic of assigning values more complex and to change fields to properties. This is where the problems emerge.
Public fields can be used as out and ref parameters. Properties cannot. This will produce uncompilable code.
Different Reflection methods are used to access fields and properties. That means any code that gets or sets values using Reflection will break, and you'll know about it only in run time.
Different IL operators are used to access fields and properties. That means cross-assembly compatibility is broken when fields are changed to properties and only one assembly is recompiled. This will make your program fail at run time.
I concour with you, if the property is just a wrapper on the field.
And the guys at Coding Horror looks like having our same opinion, I find very funny that frightened icon they use :)
http://www.codinghorror.com/blog/2006/08/properties-vs-public-variables.html
A simple program.
Here I am adding two properties and one variables. We can use properties as per our decision. But I prefer to use properties because it helps to implement some bussiness validation and can hide the business logic form calling party.
class Program
{
static void Main(string[] args)
{
Human h = new Human();
h.FirstName = "Test";
h.LastName = "User";
Console.WriteLine(h.FullName);
Console.Read();
}
}
class Human
{
public string FullName { get { return FirstName + " " + LastName; } }
public string FirstName;//{ get; set; }
public string LastName;//{ get; set; }
}

Do I need to use { get; set; } with c# fields that have no special actions when getting and setting

I have been coding classes like this:
public class ReportViewModel
{
public string Status;
public string DataSource;
public String DataStore { get; set; }
public PageMeta PageMeta { get; set; }
public ICollection<Question> List { get; set; }
}
Note that most of the fields use { get; set; } except the first two which I let Visual Studio add for me.
What I am wondering is do I really need to use { get; set; }. It seems to me that VS2010 does not automatically add this so do I need it?
You've created a class with two public fields (Status and DataSource) and three public properties (DataStore, PageMeta and List). I would advise against having public fields - and you should actually consider whether you really need all of these to be mutable properties at all.
There are various advantages to using properties over public fields, but the main one in my mind is that a property is logically part of the API of a class, whereas a field is logically an implementation detail. The property says what callers can do - a field says how a value is stored.
{ get; set; } indicate autoimplemented properties. In .NET there is a difference between properties and fields. Normally fields should be private. They are used for some specific implementation and should in most cases be internal to the class. Properties on the other hand are used to encapsulate behavior that is exposed to the consumers.
If you want them properly exposed as properties, yes.
They are different: your first two members are fields - not properties. The others are properties with auto-implemented accessors.
When you don't add the get and set you are using a field rather than a property. Which in many cases won't make a lot of difference. However, you can't databind to a field like you can with a Property. So you would lose that.
At all depends on how this class will be used.
If this is in your code, just used in your current product, then there isn't really much difference between fields (no {get;set;}) and properties (with the {get;set;}).
However in that case they probably shouldn't be public, make them internal or private instead so that it's clear that external code shouldn't use them.
If your class is going to be used by other assemblies then you should always convert public fields to properties.
The reason is that if you want to extend properties later on (i.e. add a body to the set) then your users can just get the new DLL from you. However if you've used fields then converting them to a property will look the same in the IDE, but require your users to recompile when they get the altered DLL.
Being public tells consumers that they can rely on that member being present, being a property gives you more control of how you deliver it to them.
There is a difference. The first two are fields and the remainder are auto-properties.
The second one, the compiler generates a private backing field and some boiler-plate get/set methods. These then allow you to access the properties like they were fields, but with the advantages only available to properties.
It is always recommended to hide fields behind properties, by either making them private and writing your own property around it or using an auto-property.
There's some advantages to properties. One being that properties can be made read-only, or even write-only, or read-only with an internal write-only, etc. Since they act just like methods, you can execute any arbitrary code inside of them. This is useful for when you need to implement things like INotifyPropertyChanged or if the property is actually calculated from several fields behind it.
The other advantage is encapsulation. You aren't tying yourself directly to the fields of the class, but rather the property. So if some detail about the field changes (say it goes away and becomes calculated), by using the property you are insulating yourself from those implementation details.
You should certainly look at using properties (for now adding the { get; set; }) for all cases. They are good practice in that they provide a level of encapsulation that shields the user from implementation specific details.
You do not have to, but this just coding stundart, with its pros and cons.
Consider this link for more resources:
Property Acessors

Why do we use blank get; set; accessors in C#? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
c#: why have empty get set properties instead of using a public member variable?
string name;
vs
string name {get; set;}
Assuming your get and set are blank as above, what's the point in specifying them?
It encapsulates the compiler generated field, and provides you, the class or struct developer the ability to update it internally later without breaking your API by simply modifying the get/set part that you care about.
For instance, suddenly never want to return null? You can do that by simply changing the empty get to get { return storedName ?? ""; }. Of course, it means you suddenly need to manually control the variable, but that's a small price to pay for the flexibility.
The first use is an example of a field declaration. The second use is an example of an auto-implemented property.
It is generally bad practice to provide direct access to a field. However, the .NET team noticed that a lot of getters/setters are basically just that. For example, consider the following:
// C#
public string Name
{
get { return name; }
set { name = value; }
}
// Without properties (or a Java implementation)
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
Either way, that's a lot verbosity to really just expose a field. However, it is regularly the case that, as a developer, you need to go back and change how a field is handled internally, but you do not want to break or even affect other code if you can get away with it.
That is why using direct access to fields is bad. If you provide direct access to fields, but need to change something about using the field, then all code that uses that field must change as well. If you use a property (or even a method), then you can change the internal code and potentially not effect external code.
Consider the following example:
public string Name
{
get;
set;
}
Later you decide that you need to raise a changing and changed event around the setter. If you exposed a field, then it's time for a potentially big rewrite. If you used properties (or a method), then you can just add the logic there. You suddenly lose the benefit of auto-implementing properties, but you gained the ability to refactor your class without breaking existing code.
private string name;
public event NameChangingEventHandler NameChanging;
public event NameChangedEventHandler NameChanged;
public string Name
{
get { return name; }
set
{
OnNameChanging(/*...*/);
name = value;
OnNameChanged(/*...*/);
}
}
protected virtual void OnNameChanging(/*...*/) { }
protected virtual void OnNameChanged(/*...*/) { }
All of that maintains your public API and requires no work from users of the class (the rest of your code, or external developers using of your API). Breaking changes are not always avoidable, but avoiding direct access to fields is a good step to try to ensure that it won't happen. Auto-implemented properties are a quick, and easy way to do it.
(Unrelated: lost power while typing this and I am very happy that my browser saved most of it!)
The first one is actually a Field, but the second one is an Auto-Implemented property. The difference between them has already been discussed.
The first, assuming it's declared in class scope, is a field name. It's accessed as a field. The second is a property. A Blank get/set is known as an auto-property.
You might need to actually do something in your accessors in the future. Changing a field (which is what your first declaration is) to a property is a breaking change, so specifying accessors in advance is a small investment in the future.
Being able to add logic to a field's accessors without breaking compatibility is the standard explanation, and it's certainly a big one if you're writing a library or an application that's split among several assemblies that might be updated independently. I think it's something that one could dismiss as less of a concern if you're working on any sort of "all-in-one" software, though, since it'll all be recompiled anyway.
But even then, there's still another very compelling reason to only expose properties in your public interfaces: Even if you never need to make any internal updates, using fields can still lead to other problems on down the line because many portions of the .NET framework strongly prefer properties to fields. WPF, for example, does not generally support binding to fields. You can get around that by doing fancy things like implementing ICustomTypeDescriptor, but it's just so much easier to simply type {get; set;}.
string name {get; set;}
This is called auto implemented property. Actually, C# creates variable starting with _ itself, so on get, that variable value is fetched and on set, that variable value is set. Its just like normal properties. Where as string name; is just a field.
The first is a variable, the second is a (shorthanded) property
Properties are very nice, but as a general rule, objects shouldn't expose state to the public; they should be a black box from the perspective of outsiders. And you especially shouldn't state to direct change. State should change as a side effect of asking the object instance to do something useful in the problem domain.
If you are going to expose state, expose it as a read-only property (e.g. public widget Foo { get ; private set ; }).

What is the difference between public int i and public int i {get; set;} (what is the difference between automatic property and a public member?) [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
c#: why have empty get set properties instead of using a public member variable?
C#: Public Fields versus Automatic Properties
I am using "automatic" properties in my code,
and I wonder what is the actual difference between
this code:
public class foo{
public int i;
}
and
public class foo{
public int i {get; set;}
}
I know there is a difference, as sine 3rd parties that I've used missed the public members but found them once adding the {get; set;}.
AS there is no private field behind that, what is going behind the scene ?
A private field gets generated by the compiler when using automatic properties.
When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
In regards to the difference between the two examples - the first one exposes the field directly for manipulation. This is considered bad practice (think information hiding, loss of encapsulation).
With the second example, you must use the getter and setter and you can add any kind of validation and other logic around these actions.
See this blog post:
If I have a field with no special behavior, should I write a "just in case" property (with trivial get/set), or should I expose a public field?
The reason that the library design guidelines suggest you write a property here is that it is important that libraries be easily versioned. If you put a property in there ahead of time, you can change the property implementation without requiring users to recompile their code.
The first is a field and could be described as POD. The second is a property and allow for derived classes to overload and Shadow while the first does not. Also the second is a nicety since the complier silently creates a backing store.
That's an auto property, not an anonymous property. There is, in fact, a private backing field for it, it's just generated automatically by the compiler and isn't available to you at compile time. If you run your class through something like Reflector (or examine it at runtime with reflection), you'll see the backing field.
To answer your question of "What's the difference?", the obvious answer is that one is a field, whereas one is a property. The advantage to using auto properties is that it gives you the flexibility to move to traditional properties later, should the need arise, without changing your API. As far as third party code being able to "reach" one but not the other, that would be a question best answered by the other developer. That being said, most API's are designed to work on properties, not fields (since conventional wisdom is that you do not expose fields outside of the declaring class). If the third-party library is reflectively scanning your class, then it's likely only looking for properties.
The important thing to remember is that:
private string backingField;
public string Data
{
get { return backingField; }
set { backingField = value; }
}
and
public string Data { get; set; }
Are compiled to essentially the same code. The only substantive difference is the name of the backing field.

C#: Can I remove "{ get; set; }"?

Is there a difference between:
public T RequestedValue { get; set; }
and
public T RequestedValue;
?
Taken from this code:
public class PropertyChangeRequestEventArgs<T>:EventArgs
{
public PropertyChangeRequestEventArgs(T pRequestedValue)
{
RequestedValue = pRequestedValue;
}
public T RequestedValue { get; set; }
}
The first is an Auto-Implemented Property the second is a Field. Regular Properties expose Getters and Setters but have a private field to actually store the value:
private int someProperty;
public int SomeProperty
{
get { return someProperty; }
set { someProperty = value; }
}
The first allows you to change certain aspects of the implementation of your class without affecting all the other code in your application. The most important point is that, with properties, changes can be made without breaking binary compatibility (although a field can often be changed to a property without breaking code). If it is a public member, a property is advisable. (Stealing shamelessly from Snarfblam's comment)
From the Properties page:
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
Properties with a backing field are the most flexible form as they allow easy implementation of things like the INotifyPropertyChanged event for updating the UI in Model-View-ViewModel implementations.
deep explanation!
The {get; set;} is an automatic property, while the second is a field.
a field is a normal variable, from some type, that contains data.
a property is a couple of methods (well sometimes it's just one), one for get, and one for set. they only have a syntax like fields, but actually they are quite different.
properties are usually for filtering the set of the value, or virtualizing something in the get, etc.
automatic properties, also create a private field behind the scenes, return its value in the get, and set its value in the set.
seemingly this is just like a normal field, but behind the scenes (IL) using properties is totally different from using fields.
a.Property1 = 4;
is translate into something like:
a.Set_Propert1(4);
and this:
x = a.Property1;
is translate to something like this:
x = a.Get_Property1();
so why is it a good practice to use only public properties, even if they are automatic?
say you are writing a library, that is used by other application, and someday you want to release a new version of that library that constrains one of your class' fields..
if you are using properties, you can just change the property (even if it is an automatic one, you can replace it by a full one), and then any application which used your library can still use it in the same way.
but if you made a public field, which you now want to constrain, you'll need to make a property for this and make the field private, but if you will, any application that used you library will no more be bale to, because the way it use fields and property is different.
You may write:
public T RequestedValue { get; set; }
as a shortcut of:
private T _requestedValue;
public T RequestedValue
{
get { return this._requestedValue; }
set { this._requestedValue = value; }
}
They are totally equivalent, also considering the performance.
The answer is, yes you can remove the { get; set; } but then a whole load subtle differences kick in. Some will say fields and properties express radically different design intent but in practice this distinction has been eroded over the years as C# evolves and progressively blurs the the syntactic differences.
For a good list of compiler-binary level differences between fields and properties refer to SO question difference-between-property-and-field-in-c. But the answers to that question missed one significant point about the special role of properties when declaring interfaces.

Categories

Resources