Property initializers vs old way of initializing property .Can you clarify - c#

googled but could not find an explanation of usage for property initializers
Could somebody tell me if below code is the same?are properties that uses property initializers only instantied once?
what is the difference between these 3 ways of initialize a list in terms of efficiency and best practice
1) private List<Address>Addresses
{
get
{
return addresses ?? (addresses = new List<Address>());
}
}
2) public List<Address> Addresses{ get; set; } = new List<Address>();
3) within constructor Addresses= new List<Address>()
thanks for clarifation!

Examples 2 and 3 initialize the property as soon as each instance is created.
Example 1 initializes the property lazily; it does this by initializing the backing field only at the first invocation of the property getter (when the backing field is still uninitialized). It's entirely possible that the backing field remains uninitialized for the entire lifetime of a given instance provided that instance's Addresses property is never accessed.
Whether or not lazy initialization is more efficient depends entirely on the property and how it's going to be used.
The pre-C# 6 equivalent of example 2 is not lazy initialization, but the following:
public List<Address> Addresses { get; set; }
... with initialization being done in the constructor. Declaring and initializing an auto-implemented property in the same statement is new to C# 6.

First of all, do not use concrete implementation of class for property, use interface (IList, for example). Secondly, I prefer to initialize property as your Addresses inside default constructor and then call this constructor from another.
For example:
public class MyClass1
{
public IList<MyPropertyClass1> Property1{get; protected set;}
public MyPropertyClass2 Property2{get; protected set;}
...
public MyClass1()
{
//I initialize Property1 by empty List<T>=> internal logic will not crashed if user try to set Property1 as null.
Property1=new List<MyPropertyClass1>();
Property2=default(MyPropertyClass2);
...
}
public MyClass1(IList<MyPropertyClass1> property1, MyPropertyClass2 property2)
:this()
{
if(property1!=null)
{
Property1=property1;
}
if(property2!=default(MyPropertyClass2))
{
Property2=property2;
}
}
}

Related

Why is `this` not available in C# 6.0 Auto-Property Initialization?

I have the following code class:
public class Foo
{
public Nested Bar { get; } = new Nested(this);
public class Nested
{
public Nested(Foo foo)
{
foo.DoSomething();
}
}
private void DoSomething()
{
}
}
However, I get this compile error:
Keyword 'this' is not available in the current context
I can fix it by simply not using Auto-Property Initializer, and explicitly move it into a constructor instead:
public Nested Bar { get; }
public Foo()
{
this.Bar = new Nested(this);
}
Why is it so? Isn't Auto-Property Initializer actually translated into constructor code in IL?
Simply: you can't use this in initializers. The idea is to prevent an incomplete object from escaping - Nested(this) could do anything to your object, leading to very confusing and hard to understand bugs. Keep in mind that initializers execute before any constructor that you add. The same thing fails for field initializers too, in exactly the same way:
private Nested _field = new Nested(this);
Essentially, initializers are intended to perform simple initializations - fixing the 98% problem. Anything involving this is more complex, and you'll need to write your own constructor - and take the blame for any timing issues :)
Why is it so? Isn't Auto-Property Initializer actually translated into constructor code in IL?
The rules for automatically implemented property initializers are the same as those for field initializers, for the same reason. Note that property initializers are executed before base class bodies, just like field initializers - so you're still in the context of a "somewhat uninitialized" object; more so than during a constructor body.
So you should imagine that the property is being converted into this:
private readonly Nested bar = new Nested(this); // Invalid
public Nested Bar
{
get { return bar; }
}
In short, this restriction is to stop you from getting yourself into trouble. If you need to refer to this when initializing a property, just do it manually in a constructor, as per your second example. (It's relatively rare in my experience.)

Is there any way to implement a get method inside a class in C#?

I would like to know if there is any way to implement a get method inside a class?
public class Element: IWebElement
{
IWebElement realElement;
//Question point is this get{}
//Everytime I access the instance of this class this get would be called
get
{
//This 'realElement' is not present yet
//So I cannot initialize it
//But when the properties of this class are accessed
//I'm telling the get method that it's time to initialize 'realElement'
realElement = webDriver.FindElement(...);
Visible = element.Visible;
return this;
}
public bool Visible {get; set;}
}
public class AnotherClass()
{
public void AccessElement()
{
Element element = new Element();
if(element.Visible) // At this point the 'element'
{
}
}
}
Usage:
I cannot initialize every property with their own get, because they are too many
Everytime I access the instance of this class this get would be called
If that could be done you'd be in trouble returning this since that would then access the instance, which would call the method, which would then access the instance, which would call the method… and so on until you get a StackOverflowException (or if it got tail-call optimised, forever).
More generally the question doesn't make sense.
A get method is a method identified as being the getter of a property. When C# is compiled to CIL then properties with getters are compiled so that there is a .property declaration with a .get declaration that refers to that method. If C# decided to change the rules to have getters on classes, it wouldn't have any corresponding CIL to compile it to.
The closest thing to a getter on a class in .NET is a default property, which in C# you can only have (and will always have) on a property called this (it becomes what is visible to other .NET languages or reflection property called Item), but it must have an indexer, and it does still exist as a property rather than with the getter directly applied to the class.
You could use the constructor, so it will be called everytime instance of object will be created.
public class Element()
{
public Element(){
AnyProperty = ""; //some value initialize
}
}
Added this new answer with my old answer because I got downvoted for trying to answer your original code which is now really different. Sheesh.
Usage: I cannot initialize every property with their own get, because
they are too many
So, this is actually not how you usually use get. Get is used mostly for access to a private method, or with a little logic, and oftentimes for data-binding such as in MVVM, etc.
I think your wording is not accurate. You said
Everytime I access the instance of this class this get would be called
But based on your code, what you mean is "Everytime I instantiate a class". The only thing you really need is a constructor.
public class Element: IWebElement
{
IWebElement realElement;
public bool Visible {get; set;}
public Element()
{
realElement = webDriver.FindElement(...);
Visible = element.Visible;
}
}
Old answer:
You're probably thinking of the Singleton Pattern
EDIT: This originally answered original question's code, seen below.
public class Element()
{
//Question point is this get{}
//Everytime I access the instance of this class this get would be called
get{
return this;
}
public string AnyProperty {get; set;}
}
public class AnotherClass()
{
public void AccessElement()
{
Element element = new Element();
element.AnyProperty = "";
}
}

can we access properties from constructor

I am working on a CSharp code where in constructor i need to access properties of that class. Logically it looks troublesome to me since i will be accessing properties of the object that hasn't is still under construction.
Its an old code using c# version 4.0 and i am kind of refactoring it so that's why can't redesign everything from scratch.
Thanks
class employee
{
employee()
{
int square = count * count;
}
private int count {get;set;}
}
There is nothing wrong with that, except that count will always be 0.
There is (almost) no such thing as a "partially-constructed" object in .Net, except for an object that hasn't set all of its state in the constructor.
If you're constructing the class, and none of the properties have been set previously in the constructor and none of the properties are static and set elsewhere, the values will be default or null, so there's no point getting what they contain. Otherwise, the constructor is the perfect place to set your properties to something.
At construction time you may set a property, but unless it has a static member backing the getting or is a value type, you will get a null value until you set it.
public class WhatClass
{
public WhatClass()
{
int theCount = Count; // This will set theCount to 0 because int is a value type
AProperty = new SomeOtherClass; // This is fine because the setter is totally usable
SomeOtherClass thisProperty = AProperty; // This is completely acceptable because you just gave AProperty a value;
thisProperty = AnotherProperty; // Sets thisProperty to null because you didn't first set the "AnotherProperty" to have a value
}
public int Count { get; set; }
public SomeOtherClass AProperty { get; set; }
public SomeOtherClass AnotherProperty { get; set; }
}
Yes, C# allow this, but sometime better to have private field which is wrapped by public property and in class method work only with field. In your case I would recommend to remove private property and use class field variable instead. If consumers of your class potentially may want to access a property - make it public with a private setter, this kind of autmatic property is an other alternative for privatr field wrapped by a property.

null exception with lists in c#

hey i am trying to work with a generic list in C# and for some reason after allocating memory for the list i am getting unhandeledNullException.
//edit
i found out what was my problem i did not use the properties currectly.
if lets say GeoInfo is a private member of my class, how do i do properties to it,
i tried :
private List<GeoInfo> GEOINFOS { get; set; } // edit i forgot to change it back
// but i want to have my geoinfos private and my properties public
thanks in advance for your help
You've made the properties private. If you want them to be public try:
public List<GeoInfo> GeoInfos { get; set; }
The auto-implemented value that is stored locally in the object will be private; but the properties themselves are public.
Because what you are declaring there are the property accessors.
If you want to write everything explicitly, you could do it the old pre 3.0 way
private List<GeoInfo> geoInfos = new List<GeoInfo>;
public List<GeoInfo> GeoInfos {
get { return geoInfos; }
set { geoInfos = value; }
}
This still relies on geoInfos being initialized somewhere (like the constructor) -- or nullPointerException will return.
You could do lazy-evaluation on it right in the getter:
private List<GeoInfo> geoInfos = new List<GeoInfo>;
public List<GeoInfo> GeoInfos {
get { if (geoInfos == null) {
geoInfos = new List<GeoInfo>;
}
return geoInfos;
}
set { geoInfos = value; }
}
This ensures that you don't have to specify a call in the constructor, and you don't have to worry about the execution sequence setting the element explicitly prior to getting it.
But if you use the auto-generated-properties, you will have to explicitly set the reference at some point. AS suggested elsewhere, the best bet is the constructor.
If you want a property to be private, use
private List<GeoInfo> GEOINFOS { get; set; }
However, there's not a lot of reason to use an auto property for a private member variable (and don't forget to initialize that list as well). If you want validation fine, but you're just using that property as a private variable.
Your null reference issue probably comes from not initializing the underlying property variable. That does not get done automatically, so
public MyClass()
{
GEOINFOS = new List<GeoInfo>();
}
One more thing: your naming convension for a property is odd for C#. How about keeping things consistent and sing GeoInfos?

How to implement a read only property

I need to implement a read only property on my type. Moreover the value of this property is going to be set in the constructor and it is not going to be changed (I am writing a class that exposes custom routed UI commands for WPF but it does not matter).
I see two ways to do it:
class MyClass
{
public readonly object MyProperty = new object();
}
class MyClass
{
private readonly object my_property = new object();
public object MyProperty { get { return my_property; } }
}
With all these FxCop errors saying that I should not have public member variables, it seems that the second one is the right way to do it. Is this correct?
Is there any difference between a get only property and a read only member in this case?
The second way is the preferred option.
private readonly int MyVal = 5;
public int MyProp { get { return MyVal;} }
This will ensure that MyVal can only be assigned at initialization (it can also be set in a constructor).
As you had noted - this way you are not exposing an internal member, allowing you to change the internal implementation in the future.
C# 6.0 adds readonly auto properties
public object MyProperty { get; }
So when you don't need to support older compilers you can have a truly readonly property with code that's just as concise as a readonly field.
Versioning:
I think it doesn't make much difference if you are only interested in source compatibility.
Using a property is better for binary compatibility since you can replace it by a property which has a setter without breaking compiled code depending on your library.
Convention:
You are following the convention. In cases like this where the differences between the two possibilities are relatively minor following the convention is better. One case where it might come back to bite you is reflection based code. It might only accept properties and not fields, for example a property editor/viewer.
Serialization
Changing from field to property will probably break a lot of serializers. And AFAIK XmlSerializer does only serialize public properties and not public fields.
Using an Autoproperty
Another common Variation is using an autoproperty with a private setter. While this is short and a property it doesn't enforce the readonlyness. So I prefer the other ones.
Readonly field is selfdocumenting
There is one advantage of the field though:
It makes it clear at a glance at the public interface that it's actually immutable (barring reflection). Whereas in case of a property you can only see that you cannot change it, so you'd have to refer to the documentation or implementation.
But to be honest I use the first one quite often in application code since I'm lazy. In libraries I'm typically more thorough and follow the convention.
With the introduction of C# 6 (in VS 2015), you can now have get-only automatic properties, in which the implicit backing field is readonly (i.e. values can be assigned in the constructor but not elsewhere):
public string Name { get; }
public Customer(string name) // Constructor
{
Name = name;
}
private void SomeFunction()
{
Name = "Something Else"; // Compile-time error
}
And you can now also initialise properties (with or without a setter) inline:
public string Name { get; } = "Boris";
Referring back to the question, this gives you the advantages of option 2 (public member is a property, not a field) with the brevity of option 1.
Unfortunately, it doesn't provide a guarantee of immutability at the level of the public interface (as in #CodesInChaos's point about self-documentation), because to a consumer of the class, having no setter is indistinguishable from having a private setter.
In C# 9, Microsoft introduced a new way to have properties set only on initialization using the init accessor, like so:
public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
This way, you can assign values when initializing a new object:
var person = new Person
{
Firstname = "John",
LastName = "Doe"
}
But later on, you cannot change it:
person.LastName = "Denver"; // throws a compiler error
You can do this:
public int Property { get { ... } private set { ... } }
I agree that the second way is preferable. The only real reason for that preference is the general preference that .NET classes not have public fields. However, if that field is readonly, I can't see how there would be any real objections other than a lack of consistency with other properties. The real difference between a readonly field and get-only property is that the readonly field provides a guarantee that its value will not change over the life of the object and a get-only property does not.
yet another way (my favorite), starting with C# 6
private readonly int MyVal = 5;
public int MyProp => MyVal;
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties#expression-body-definitions
The second method is preferred because of the encapsulation. You can certainly have the readonly field be public, but that goes against C# idioms in which you have data access occur through properties and not fields.
The reasoning behind this is that the property defines a public interface and if the backing implementation to that property changes, you don't end up breaking the rest of the code because the implementation is hidden behind an interface.

Categories

Resources