How can i serialize property of c# in Unity - c#

I think it's inefficient to implement these two lines of variables.
[SerializeField] private int i;
public int I => i;
So I would like to express this in one line, but this is not serialized in Unity.
[SerializeField] public int I { get; private set; }
I want to make it visible in Unity Inspector.
So my question is below.
Can this property be serialized?
If impossible, is it possible to solve it in a way other than the above?

Starting in C# 7.3 (which Unity supports), you can now add attributes to the backing fields generated by autoproperties.
For this instance, where the backing field is auto generated, you can add this attribute:
[field: SerializeField] public int MyField { get; private set; }
This serializes the backing field as if it were a normal variable.

Well that's correct behavior.
[SerializeField]
public int I { get; private set; }
This is a property (with a getter and setter accessor), not a variable. These are not, cannot and should not be serialized. If you want an exposed variable that you can set (or see) in the Inspector, use a public modifier on a variable, not a function or accessor. If you don't want the variable to be public, then it can be protected or private, but marked with [SerializeField] as you already know. This is by design and is the correct approach.
Some additional information as it seems you might have different expectations on how Unity should behave:
Unity has some different paradigms as opposed to conventional programming and this is by design as the engine has a different approach to how each game object (and by this I mean any UnityEngine.Object descendant, not just UnityEngine.GameObject) interacts with another and how it should be implemented in the game (i.e. adding it as a Component or ScriptableObject as opposed to using new() or how the garbage collection of said objects is handled in the engine). This means that if you want the convenience of the Inspector real-time editing features, you'll need to "break" some rules regarding object access and mark a lot of variables as public. If you don't want that, there's always the option of referencing them in code or using ScriptableObjects, but that might be overkill in some cases.
Unity is also akin to encapsulated, as extending existing deployments is done differently from C#, so using public or private variables or functions doesn't change much. It's not like somebody is going to make a library and extend from your game's library since Unity doesn't work that way.

Related

Strange line in C# camera code

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.

Unity5 Private vs Public Gameobject

what is the difference between public and private variables , gameobjects and other things in Unity - C# ? ; Thanks for help.
The public variables can easily be changed, while the private variables cannot be easily changed.If you compile the code you can see an input for the public variable in the inspector panel, by changing the variable in the inspector panel you change the variable for that case. However, you will not see one for a private variable.
I would suggest for scripts in which will be use more than 1 times, expose the elements that would be used differently.
If a variable/function is public, other classes with access to the class can access it.
If a variable/function is private, other classes can't access it. Only the class itself can use it.
Good programs try to have as few public variables/functions as possible, see Loose coupling.

Using a private auto property instead of a simple variable for a programming standard

In a discussion with a peer, it was brought up that we should consider using auto properties for all class level variables... including private ones.
So in addition to a public property like so:
public int MyProperty1 { get; set; }
Our private class-level variables would look like this:
private int MyProperty2 { get; set; }
Instead of:
private int _myProperty2;
I'm on the fence about why someone would want to do this but I can't decide if my reluctance to accept this is because of my own internal brainwashing with how I write my code to the same programming standards and naming conventions I've used for 10 years or because I've never seen this before (for a reason).
I realize it's extra code to type but to be honest, when using auto-properties, I don't think I've ever typed it out due to the 'prop' and 'propg' snippets so it'd be very simple to set up a new snippet to create a private auto property so the extra code doesn't bother me too much since I never have to type it.
Other than aesthetics which may just be my subconscious, are there any issues that could result from using fully private auto properties? Are there any good reasons to do this or not to do it? I've seen a lot of code in my day on stackoverflow, codeplex, codeproject, etc. and I've never seen anyone use this standard.... is there a reason why?
Private auto-properties are completely pointless, in my opinion. What value does a private auto-property provide that a plain field doesn't?
(It's different when the auto-property is only partially private -- eg, a public/protected getter with a private setter -- or when you use a private non-automatic property to enable you to wrap additional code around the getter/setter.)
This does not make too much sense.
I can think of a 'benefit':
you can later add logic to the getter and/or setter and be sure it is always passed
but frankly your classes should not become so big that this is useful.
"are there any issues" ?
Your properties won't work as arguments to ref or out parameters.
It's not nearly as useful for privates as for publics.
Suppose you took your automatic private property and later built some logic into it (being able to do that without breaking anything is the whole point of auto props)...
This would require you to create a private backing member for the property to wrap.
So now you've got two different private ways (member and property) of doing the same thing though one has hidden side effects (the property) and you've now also got the problem of ensuring none of your other methods in the class access that member directly.
Ends up being much more of a headache than just using a private member from the beginning.
What this strategy will do for you is provide an opportunity to put any future changes into the previously autogenerated private property without affecting any of the other code that gets or sets your private property. I personally haven't used this much but it can be beneficial in a case where changes to handling may occur. It also standardizes the code so that fields are always accessed by properties. There are no real drawbacks but it is not really much benefit in most situations either. I think style is really the biggest driver in most situations.
In a discussion with a peer, it was
brought up that we should consider
using auto properties for all class
level variables... including private
ones.
This will not be useful, In case you don't have any logic to write in your properties for retrieving and returning values.
Besides point 1, you have read only property
So you can directly go with
public int MyProperty1 { get; set; }
Moreover it reduces your line of code and Quick Implementation
I'm a firm believer in KISS. I never use a property when a field will do, and I see very little reason to use private accessors (get).
The primary purpose of a property is to be a public accessor for private data. So for simple propreties that do nothing but set or get a value, private accessors and setters make no sense.
Having said that, when you need to transform the data as it's being read, or when you need to perform a side effect when updating the value, you should use a field. Does changing your value raise an event? Then a field is a no-brainer. But then, that's not an auto field that you're declaring with {get; 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.

Should you access a variable within the same class via a Property?

If you have a Property that gets and sets to an instance variable then normally you always use the Property from outside that class to access it.
My question is should you also always do so within the class? I've always used the Property if there is one, even within the class, but would like to hear some arguments for and against as to which is the most correct and why.
Or is it just a matter of coding standards being used on the project?
One of the stronger argument for accessing local (class scope) variables through properties is that you add a level of abstraction in your class. If you change any logic concerning how that field is stored then the rest of your code will be left unaffected.
For example you might change that from a local variable to a property of a child object, to a database call, to a webservice call, to a static property on a class and so on. When making the change it gives you a single point of change, the property, and you do not have to update the rest of your class since they all use the property.
Also using the property enables you to apply business rules on the value of the property instead of having to enforce the same rule at each location where you'd directly access the field. Again, encapsulation
With the introduction of automatic properties there's even less reason to explicitly have a local variable, unless you need to apply business rules on the get/set
It depends on whether you want to apply any logic implemented within the property setter, and so you really have to decide on a case by case basis.
When you go directly to the private field, you know that the field is being set to exactly what you say.
When you go through the Property, the value gets set according to the setter logic, so you get any business rules or validation you want over values assigned to that field.
Pretty hard to come up with a rule about when doing either is 'correct', about the only one I'd say I follow is that in constructor initialisation I'd pretty much never use the Property.
Yes I think you should use properties internally in your classes whenever possible. Properties are more flexible and allows you to add logic for validating it's value at a central place.
You can also delay the initialization of the the field to whenever the property is used instead of being forced to do it in the constructor (or everywhere the field is used). Example:
class Test {
private int _checksum = -1;
private int Checksum {
get {
if (_checksum == -1)
_checksum = calculateChecksum();
return checksum;
}
}
}
I think it's purely preference.
Though, I find myself using the properties a lot more in C# 3.0 with the auto-property support:
class Foo {
public string Value { get; set; }
public void Write() {
Console.Write(Value);
}
}
Generally depending on the project coding standards I use a "_" or "m" preceding the name for my private class attributes. (Like below)
private int mVariable;
private int _Variable;
With those in front of the variable I recognize right away that I'm dealing with an internal variable for the class. Then when it comes to debugging later myself or someone else can immediately recognize that the code is dealing with an internal private variable and make an adjustment. So it comes down to readability for me.
Always Use Properties, Here are some of the reasons
Easy to Use. In visual Studio you can use "Prop Tab Tab". You will get the property snippet
Properties are language elements that are accessed as though they are data members
.Net framework classes uses it, the data binding code classes in the .NET Framework support properties,
Properties have all the language features of methods. Properties can be virtual

Categories

Resources