Expression-bodied members doesn't create new instances? - c#

I'm curiuous why Expression-bodied properties doesn't create persisant objects.
public List<string> Pages { get; } = new List<string>();
Does create a persistant isntance of List<string>, just like always.
But
public List<string> Pages => new List<string>();
Somehow this does craete a new instance, but seems to be volatile.
Even when adding a new string to Pages won't add it.
There's no runtime- nor compile-time error, but I think there should be at least a warning.
It took me quite a while to figure it out.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members
Is a bit odd documented.

Properties noted with { get; } have an internal field that stores the value. However, the second example which is expression-bodied, declares the creation of the list as the getter, which means it will be ran every time you access it, and every time it creates a new list.
As noted in comments, it is the same as get { return new List<string>(); }, to explain it in a different way.
To change this behavior, you need to have an internal field which would store the List instance and the expression-bodied member to return it.

Following the link in the documentation you linked, we have read-only properties:
Starting with C# 6, you can use expression body definition to implement a read-only property. To do that, use the following syntax:
PropertyType PropertyName => expression;
The following example defines a Location class whose read-only Name property is implemented as an expression body definition that returns the value of the private locationName field:
public class Location
{
private string locationName;
public Location(string name)
{
locationName = name;
}
public string Name => locationName;
}
(Emphasis mine)
To rephrase it: when you access the Name property, the value held by locationName is returned. If the value of locationName changes, and you access Name again, you get the new value of locationName.
It's equivalent to:
public string Name
{
get => locationName;
}
Or
public string Name
{
get { return locationName; }
}

Related

C# 9 require property set at construction without explicit constructor [duplicate]

I have requirement in a custom class where I want to make one of my properties required.
How can I make the following property required?
public string DocumentType
{
get
{
return _documentType;
}
set
{
_documentType = value;
}
}
If you mean "the user must specify a value", then force it via the constructor:
public YourType(string documentType) {
DocumentType = documentType; // TODO validation; can it be null? blank?
}
public string DocumentType {get;private set;}
Now you can't create an instance without specifying the document type, and it can't be removed after that time. You could also allow the set but validate:
public YourType(string documentType) {
DocumentType = documentType;
}
private string documentType;
public string DocumentType {
get { return documentType; }
set {
// TODO: validate
documentType = value;
}
}
.NET 7 or newer
Syntax
public class MyClass
{
public required string Name { get; init; }
}
new MyClass(); // illegal
new MyClass { Name = "Me" }; // works fine
Remarks
The required properties must declare a setter (either init or set).
Access modifiers on properties or setters cannot be less visible than their containing type, as they would make impossible to initialize the class in some cases.
public class MyClass
{
internal required string Name { get; set; } // illegal
}
Documentation
Official documentation here
Feature demo here
.NET 6 or older
See this answer
If you mean you want it always to have been given a value by the client code, then your best bet is to require it as a parameter in the constructor:
class SomeClass
{
private string _documentType;
public string DocumentType
{
get
{
return _documentType;
}
set
{
_documentType = value;
}
}
public SomeClass(string documentType)
{
DocumentType = documentType;
}
}
You can do your validation – if you need it – either in the property's set accessor body or in the constructor.
With the release of .NET 7 and C# 11 in November 2022 you can now use the required modifier this way:
public class Person
{
public Person() { }
[SetsRequiredMembers]
public Person(string firstName) => FirstName = firstName;
public required string FirstName { get; init; }
public int Age { get; set; }
}
And when you don't have the required properties it will throw an error when you try to initialize an object.
For more information refer to:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#required-members
https://learn.microsoft.com/en-us/dotnet/csharp/properties#init-only
Add a required attribute to the property
Required(ErrorMessage = "DocumentTypeis required.")]
public string DocumentType
{
get
{
return _documentType;
}
set
{
_documentType = value;
}
}
For custom attribute detail Click Here
I used an other solution, not exactly what you want, but worked for me fine because I declare the object first and based on specific situation I have different values. I didnt want to use the constructor because I then had to use dummy data.
My solution was to create Private Sets on the class (public get) and you can only set the values on the object by methods. For example:
public void SetObject(string mandatory, string mandatory2, string optional = "", string optional2 = "")
This one liner works in C# 9:
public record Document(string DocumentType);
new Document(); // compiler error
new Document("csv"); // correct way to construct with required parameter
This explains how it works. In the above code, Document is the name of the class or "record". That first line of code actually defines an entire class. In addition to this solution essentially making a required DocumentType property (required by an auto implemented constructor), because it uses records, there are additional implications. So this may not always be an appropriate solution, and the C# 11 required keyword will still come in handy at times. Just using record types doesn't automatically make properties required. The above code is a special syntax way of using records that essentially has this effect as well as making the property init only and causes a deconstructor to be automatically implemented.
A better example would be using an int property instead of a string since a string could still be empty. Unfortunately I don't know of any good way to do extra validation within the record to make sure the string is not empty or an int is in range, etc. You would have to go deeper down the TOP (type driven development) rabbit hole, which may not be a bad thing. You could create your own type that doesn't allow empty strings or integers outside your accepted range. Unfortunately such an approach would lead to runtime discovery of invalid input instead of compile time. There might be a better way using static analysis and metadata, but I've been away from C# for too long to know anything about that.

Solution for CA2227 or better approach?

I'm only using Code Analysis for cleaning, organizing and ensuring these changes are globally performed for all instances of a particular warning. I'm down to the final, and it's CA2227.
CA2227 Collection properties should be read only Change '' to be
read-only by removing the property setter.
Note this is for mapping of EDI documents. These classes are to represent a whole or part of an EDI document.
public class PO1Loop
{
public SegmentTypes.PO1LoopSegmentTypes.PO1 PO1 { get; set; }
public Collection<SegmentTypes.PO1LoopSegmentTypes.PID1> PIDRepeat1 { get; set; }
public Collection<SegmentTypes.PO1LoopSegmentTypes.PID2> PIDRepeat2 { get; set; }
public SegmentTypes.PO1LoopSegmentTypes.PO4 PO4 { get; set; }
/* Max Use: 8 */
public Collection<SegmentTypes.PO1LoopSegmentTypes.ACK> ACKRepeat { get; set; }
}
You can see all of the Collection properties will give me this warning, and there are hundreds of them. When using the above class I instantiate it without any data. Then externally I add the data and set each individual variable through its public accessor. I do not instantiate this class with all the data prepared and passed using a constructor method (IMO for the size these can reach it can easily wreak havoc on the eyes). When complete and all properties are assigned the class as a whole is then used to generate that part of a document it represents.
My question is, for the usage described above, what would be a better approach for setting this up correctly? Do I keep the public accessors and suppress this warning entirely, or is there a entirely different solution that would work?
Here's what MSDN says about the error, and also how you can avoid it.
Here's my take on the issue.
Consider, the following class:
class BigDataClass
{
public List<string> Data { get; set; }
}
This class will throw that exact same issue. Why? Because Collections do not need a setter. Now, we can do anything with that object: assign Data to an arbitrary List<string>, add elements to Data, remove elements from Data, etc. If we remove the setter, we only lose the ability to directly assign to that property.
Consider the following code:
class BigDataClass
{
private List<string> data = new List<string>();
public List<string> Data { get { return data; } } // note, we removed the setter
}
var bigData = new BigDataClass();
bigData.Data.Add("Some String");
This code is perfectly valid and in fact the recommended way to do things. Why? Because the List<string> is a reference to a memory location, that contains the remainder of the data.
Now, the only thing you cannot now do with this, is directly set the Data property. I.e. the following is invalid:
var bigData = new BigDataClass();
bigData.Data = new List<string>();
This is not necessarily a bad thing. You'll notice that on many .NET types this model is used. It's the basics of immutability. You usually do not want direct access to the mutability of Collections, as this can cause some accidental behavior that has strange issues. This is why Microsoft recommends you omit setters.
Example:
var bigData = new BigDataClass();
bigData.Data.Add("Some String");
var l2 = new List<string>();
l2.Add("String 1");
l2.Add("String 2");
bigData.Data = l2;
Console.WriteLine(bigData.Data[0]);
We might be expecting Some String, but we'll get String 1. This also means that you cannot reliably attach events to the Collection in question, so you cannot reliably determine if new values are added or values are removed.
A writable collection property allows a user to replace the collection with a completely different collection.
Essentially, if you only ever need to run the constructor, or assignment, once, then omit the set modifier. You won't need it, direct assignment of collections is against best-practices.
Now, I'm not saying never use a setter on a Collection, sometimes you may need one, but in general you should not use them.
You can always use .AddRange, .Clone, etc. on the Collections, you only lose the ability of direct assignment.
Serialization
Lastly, what do we do if we wish to Serialize or Deserialize a class that contains our Collection without a set? Well, there is always more than one way to do it, the simplest (in my opinion) is to create a property that represents the serialized collection.
Take our BigDataClass for example. If we wished to Serialize, and then Deserialize this class with the following code, the Data property would have no elements.
JavaScriptSerializer jss = new JavaScriptSerializer();
BigDataClass bdc = new BigDataClass();
bdc.Data.Add("Test String");
string serd = jss.Serialize(bdc);
Console.WriteLine(serd);
BigDataClass bdc2 = jss.Deserialize<BigDataClass>(serd);
So, to fix this, we can simply modify our BigDataClass a bit to make it use a new string property for Serialization purposes.
public class BigDataClass
{
private List<string> data = new List<string>();
[ScriptIgnore]
public List<string> Data { get { return data; } } // note, we removed the setter
public string SerializedData { get { JavaScriptSerializer jss = new JavaScriptSerializer(); return jss.Serialize(data); } set { JavaScriptSerializer jss = new JavaScriptSerializer(); data = jss.Deserialize<List<string>>(value); } }
}
Another option is always the DataContractSerializer (which is really a better option, in general.) You can find information about it on this StackOverflow question.
With current VS2019 we can simply do this:
public List<string> Data { get; } = new List<string>();
This satisfies CA2227 and can be serialized/deserialized.
The deserialization works because List<> has an "Add" method, and the serializer knows how to handle a read-only collection property with an Add method (the property is read-only but not the elements) (I use Json.Net, other serializers may behave differently).
Edit:
As pointed out it should be "=" and not "=>" (compiler will prevent you using "=>"). If we used "public List Data => new List();" then it would create a new list every time the property was accessed which is not what we want either.
Edit:
Note that this will NOT work if the type of the property is an interface, such as IList
Edit:
I think the handling of interfaces is determined by the serializer used. The following works perfectly. I'm sure all common serializers know how to handle ICollection. And if you have some custom interface that does not implement ICollection then you should be able to configure the serializer to handle it, but in that case CA2227 probably won't be triggered making it irrelevant here. (As it is a read-only property you have to assign a concrete value within the class so it should always be serializing and de-serializing a non-null value)
public class CA2227TestClass
{
public IList Data { get; } = new List<string>();
}
[TestMethod]
public void CA2227_Serialization()
{
var test = new CA2227TestClass()
{
Data = { "One", "Two", "Three" }
};
var json = JsonConvert.SerializeObject(test);
Assert.AreEqual("{\"Data\":[\"One\",\"Two\",\"Three\"]}", json);
var jsonObject = JsonConvert.DeserializeObject(json, typeof(CA2227TestClass)) as CA2227TestClass;
Assert.IsNotNull(jsonObject);
Assert.AreEqual(3, jsonObject.Data.Count);
Assert.AreEqual("One", jsonObject.Data[0]);
Assert.AreEqual("Two", jsonObject.Data[1]);
Assert.AreEqual("Three", jsonObject.Data[2]);
Assert.AreEqual(typeof(List<string>), jsonObject.Data.GetType());
}
💡 Alternative Solution 💡
In my situation, making the property read-only was not viable because the whole list (as a reference) could change to a new list.
I was able to resolve this warning by changing the properties' setter scope to be internal.
public List<Batch> Batches
{
get { return _Batches; }
internal set { _Batches = value; OnPropertyChanged(nameof(Batches)); }
}
Note one could also use private set...
The hint's (achilleas heal) of this warning seems really pointed to libraries for the documentation says (Bolding mine):
An externally visible writable property is a type that implements
System.Collections.ICollection.
For me it was, "Ok, I won't make it viewable externally...." and internal was fine for the app.
Thanks to #Matthew, #CraigW and #EBrown for helping me understanding the solution for this warning.
public class PO1Loop
{
public SegmentTypes.PO1LoopSegmentTypes.PO1 PO1 { get; set; }
public Collection<SegmentTypes.PO1LoopSegmentTypes.PID1> PIDRepeat1 { get; private set; }
public Collection<SegmentTypes.PO1LoopSegmentTypes.PID2> PIDRepeat2 { get; private set; }
public SegmentTypes.PO1LoopSegmentTypes.PO4 PO4 { get; set; }
/* Max Use: 8 */
public Collection<SegmentTypes.PO1LoopSegmentTypes.ACK> ACKRepeat { get; private set; }
public PO1Loop()
{
PIDRepeat1 = new Collection<SegmentTypes.PO1LoopSegmentTypes.PID1>();
PIDRepeat2 = new Collection<SegmentTypes.PO1LoopSegmentTypes.PID2>();
ACKRepeat = new Collection<SegmentTypes.PO1LoopSegmentTypes.ACK>();
}
}
When wanting to assign data to the collection types use AddRange, Clear or any other variation of method for modifying a collection.
Only while binding DTO, you need to suppress warnings.
otherwise a custom ModelBinder is required custom ModelBinder to bind collections.
quoting the rule documentation:
When to suppress warnings
You can suppress the warning if the property is part of a Data Transfer Object (DTO) class.
Otherwise, do not suppress warnings from this rule.
https://learn.microsoft.com/pt-br/visualstudio/code-quality/ca2227?view=vs-2019
DTOs often require serialization and deserialization. Thus, they are required to be mutable.
Having to create an alternate backing property is a pain.
Simply change the property type from List<string> to IReadOnlyList<string> then this works as expected without CA2227.
The collection is set via the property but you can also cast to List<string> if you wish to append or delete items.
class Holder
{
public IReadOnlyList<string> Col { get; set; } = new List<string>();
}
var list = new List<string> { "One", "Two" };
var holder = new Holder() { Col = list } ;
var json = JsonConvert.SerializeObject(holder);
// output json {"Col":["One","Two"]}
var deserializedHolder = JsonConvert.DeserializeObject<Holder>(json);
I had to fix some of the CA2227 violations, so i had to add the "readonly" keyword to the collection field and then of course, had to remove the setter property. Some code that have used the setter, just created a new collection object which initially was empty. This code sure did not compile so i had to add a SetXxx() method in order to realize the missing setter's functionality. I did it like this:
public void SetXxx(List<string> list)
{
this.theList.Clear();
this.theList.AddRange(list);
}
The code of callers using the setter has been replaced with a call to the method SetXxx().
Instead of creating a complete new list, the existing list now will be cleared and filled with new items from another list, passed in as a parameter. The original list, due to the fact it is readonly and created only once, will always remain.
I believe this is also a good way to avoid that the garbagae collector has to delete old objects that got out of scope and second, to create new collection objects although there is already one.
As an addition to Der Kommissar's excellent answer.
Starting with .NET 5 (C# 9.0) there are init-only properties. These properties are only settable under specific circumstances, see here for reference.
The following example should not raise a warning CA2227, yet still allow for the collection being set during object initialization.
using System.Collections.Generic;
namespace BookStore
{
public class BookModel
{
public ICollection<string> Chapters { get; init; }
}
}
Note that the current version of the .NET SDK still raises a warning when using the built-in analyzer (not the NuGet package). This is a known bug and should be fixed in the future.
To cover all the possible scenarios to resolve CA2227 error:
This covers the Entity relationship mapping when we use Entity Framework.
class Program
{
static void Main(string[] args)
{
ParentClass obj = new ParentClass();
obj.ChildDetails.Clear();
obj.ChildDetails.AddRange();
obj.LstNames.Clear();
obj.LstNames.AddRange();
}
}
public class ChildClass
{ }
public class ParentClass
{
private readonly ICollection<ChildClass> _ChildClass;
public ParentClass()
{
_ChildClass = new HashSet<ChildClass>();
}
public virtual ICollection<ChildClass> ChildDetails => _ChildClass;
public IList<string> LstNames => new List<string>();
}

How do I modify the value of an element in a list of type class containing a string and an integer?

I'm new to programming so this is probably a very elementary question. I created a list of a class which contains an integer and a string and I want to change the integer value of a specific index and/or the string name of a specific index. Here is my code:
class Sales
{
public Sales(string name, int quantitySold)
{
Name = name;
QuantitySold = quantitySold;
}
public string Name { get; set; }
public int QuantitySold { get; set; }
}
class Restaurant
{
private List<Sales> _quantityHistory = new List<Sales>();
public List<Sales> QuantityHistory
{
get { return _quantityHistory; }
}
}
If you want to change the property of an object it is fairly simple, let me walk you through it.
Sales mySale = new Sales()
This is going to be our object, at the moment it is empty as we have just initialized an empty variable, but what if we want to initialize it with a value? Well we can do this:
Sales mySale = new Sales()
{
Name = "SaleName",
QuantitySold = 5,
};
EDIT just realised your objects constructor is initializing variables that are passed in as parameters! You don't actually need to have those in the constructor if you have getters and setters and you use the method of creating a variable that I just did above this!
Basically we you first declare the property name that the object holds, followed by the value.
But what if we want to change it somewhere down the track? Well lets pretend that so far in our code we have done exactly like we did above, somewhere down the track somebody makes a purchase so we need to add one more to the QuantitySold of the object, well thats simple just do this:
mySale.QuantitySold = mySale.QuantitySold++;
Same as the name if we need to change it!
mySale.Name = "TheNewSaleName";
Basically we just use the variable name of the object we created, followed by a fullstop and the property name and we can change it however we want!
When using a list of objects you can simply search using the index of the list, for instance:
_quantityHistory[2].Name = "TheNewNameOfThe3rdObject";
Hope this helped buddy.

What is the { get; set; } syntax in C#?

I am learning ASP.NET MVC and I can read English documents, but I don't really understand what is happening in this code:
public class Genre
{
public string Name { get; set; }
}
What does this mean: { get; set; }?
It's a so-called auto property, and is essentially a shorthand for the following (similar code will be generated by the compiler):
private string name;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
So as I understand it { get; set; } is an "auto property" which just like #Klaus and #Brandon said is shorthand for writing a property with a "backing field." So in this case:
public class Genre
{
private string name; // This is the backing field
public string Name // This is your property
{
get => name;
set => name = value;
}
}
However if you're like me - about an hour or so ago - you don't really understand what properties and accessors are, and you don't have the best understanding of some basic terminologies either. MSDN is a great tool for learning stuff like this but it's not always easy to understand for beginners. So I'm gonna try to explain this more in-depth here.
get and set are accessors, meaning they're able to access data and info in private fields (usually from a backing field) and usually do so from public properties (as you can see in the above example).
There's no denying that the above statement is pretty confusing, so let's go into some examples. Let's say this code is referring to genres of music. So within the class Genre, we're going to want different genres of music. Let's say we want to have 3 genres: Hip Hop, Rock, and Country. To do this we would use the name of the Class to create new instances of that class.
Genre g1 = new Genre(); //Here we're creating a new instance of the class "Genre"
//called g1. We'll create as many as we need (3)
Genre g2 = new Genre();
Genre g3 = new Genre();
//Note the () following new Genre. I believe that's essential since we're creating a
//new instance of a class (Like I said, I'm a beginner so I can't tell you exactly why
//it's there but I do know it's essential)
Now that we've created the instances of the Genre class we can set the genre names using the 'Name' property that was set way up above.
public string Name //Again, this is the 'Name' property
{ get; set; } //And this is the shorthand version the process we're doing right now
We can set the name of 'g1' to Hip Hop by writing the following
g1.Name = "Hip Hop";
What's happening here is sort of complex. Like I said before, get and set access information from private fields that you otherwise wouldn't be able to access. get can only read information from that private field and return it. set can only write information in that private field. But by having a property with both get and set we're able do both of those functions. And by writing g1.Name = "Hip Hop"; we are specifically using the set function from our Name property
set uses an implicit variable called value. Basically what this means is any time you see "value" within set, it's referring to a variable; the "value" variable. When we write g1.Name = we're using the = to pass in the value variable which in this case is "Hip Hop". So you can essentially think of it like this:
public class g1 //We've created an instance of the Genre Class called "g1"
{
private string name;
public string Name
{
get => name;
set => name = "Hip Hop"; //instead of 'value', "Hip Hop" is written because
//'value' in 'g1' was set to "Hip Hop" by previously
//writing 'g1.Name = "Hip Hop"'
}
}
It's Important to note that the above example isn't actually written in the code. It's more of a hypothetical code that represents what's going on in the background.
So now that we've set the Name of the g1 instance of Genre, I believe we can get the name by writing
console.WriteLine (g1.Name); //This uses the 'get' function from our 'Name' Property
//and returns the field 'name' which we just set to
//"Hip Hop"
and if we ran this we would get "Hip Hop" in our console.
So for the purpose of this explanation I'll complete the example with outputs as well
using System;
public class Genre
{
public string Name { get; set; }
}
public class MainClass
{
public static void Main()
{
Genre g1 = new Genre();
Genre g2 = new Genre();
Genre g3 = new Genre();
g1.Name = "Hip Hop";
g2.Name = "Rock";
g3.Name = "Country";
Console.WriteLine ("Genres: {0}, {1}, {2}", g1.Name, g2.Name, g3.Name);
}
}
Output:
"Genres: Hip Hop, Rock, Country"
Those are automatic properties
Basically another way of writing a property with a backing field.
public class Genre
{
private string _name;
public string Name
{
get => _name;
set => _name = value;
}
}
It is a shortcut to expose data members as public so that you don't need to explicitly create a private data members. C# will creates a private data member for you.
You could just make your data members public without using this shortcut but then if you decided to change the implementation of the data member to have some logic then you would need to break the interface. So in short it is a shortcut to create more flexible code.
This is the short way of doing this:
public class Genre
{
private string _name;
public string Name
{
get => _name;
set => _name = value;
}
}
Basically, it's a shortcut of:
class Genre{
private string genre;
public string getGenre() {
return this.genre;
}
public void setGenre(string theGenre) {
this.genre = theGenre;
}
}
//In Main method
genre g1 = new Genre();
g1.setGenre("Female");
g1.getGenre(); //Female
Basically it helps to protect your data. Consider this example without setters and getter and the same one with them.
Without setters and getters
Class Student
using System;
using System.Collections.Generic;
using System.Text;
namespace MyFirstProject
{
class Student
{
public string name;
public string gender;
public Student(string cName, string cGender)
{
name = cName;
gender= cGender;
}
}
}
In Main
Student s = new Student("Some name", "Superman"); //Gender is superman, It works but it is meaningless
Console.WriteLine(s.Gender);
With setters and getters
using System;
using System.Collections.Generic;
using System.Text;
namespace MyFirstProject
{
class Student
{
public string name;
private string gender;
public Student(string cName, string cGender)
{
name = cName;
Gender = cGender;
}
public string Gender
{
get { return gender; }
set
{
if (value == "Male" || value == "Female" || value == "Other")
{
gender = value;
}
else
{
throw new ArgumentException("Invalid value supplied");
}
}
}
}
}
In Main:
Student s = new Student("somename", "Other"); // Here you can set only those three values otherwise it throws ArgumentException.
Console.WriteLine(s.Gender);
Its an auto-implemented property for C#.
The get/set pattern provides a structure that allows logic to be added during the setting ('set') or retrieval ('get') of a property instance of an instantiated class, which can be useful when some instantiation logic is required for the property.
A property can have a 'get' accessor only, which is done in order to make that property read-only
When implementing a get/set pattern, an intermediate variable is used as a container into which a value can be placed and a value extracted. The intermediate variable is usually prefixed with an underscore.
this intermediate variable is private in order to ensure that it can only be accessed via its get/set calls. See the answer from Brandon, as his answer demonstrates the most commonly used syntax conventions for implementing get/set.
They are the accessors for the public property Name.
You would use them to get/set the value of that property in an instance of Genre.
That is an Auto-Implemented Property. It's basically a shorthand way of creating properties for a class in C#, without having to define private variables for them. They are normally used when no extra logic is required when getting or setting the value of a variable.
You can read more on MSDN's Auto-Implemented Properties Programming Guide.
This mean that if you create a variable of type Genre, you will be able to access the variable as a property
Genre oG = new Genre();
oG.Name = "Test";
In the Visual Studio, if you define a property X in a class and you want to use this class only as a type, after building your project you will get a warning that says "Field X is never assigned to, and will always has its default value".
By adding a { get; set; } to X property, you will not get this warning.
In addition in Visual Studio 2013 and upper versions, by adding { get; set; } you are able to see all references to that property.
Its basically a shorthand. You can write public string Name { get; set; } like in many examples, but you can also write it:
private string _name;
public string Name
{
get { return _name; }
set { _name = value ; } // value is a special keyword here
}
Why it is used? It can be used to filter access to a property, for example you don't want names to include numbers.
Let me give you an example:
private class Person {
private int _age; // Person._age = 25; will throw an error
public int Age{
get { return _age; } // example: Console.WriteLine(Person.Age);
set {
if ( value >= 0) {
_age = value; } // valid example: Person.Age = 25;
}
}
}
Officially its called Auto-Implemented Properties and its good habit to read the (programming guide).
I would also recommend tutorial video C# Properties: Why use "get" and "set".
Such { get; set; } syntax is called automatic properties, C# 3.0 syntax
You must use Visual C# 2008 / csc v3.5 or above to compile.
But you can compile output that targets as low as .NET Framework 2.0 (no runtime or classes required to support this feature).
Get set are access modifiers to property.
Get reads the property field.
Set sets the property value.
Get is like Read-only access.
Set is like Write-only access.
To use the property as read write both get and set must be used.
Get is invoked when the property appears on the right-hand side (RHS)
Set is invoked when the property appears on the left-hand side (LHS)
of '=' symbol
For an auto-implemented property, the backing field works behind the scene and not visible.
Example:
public string Log { get; set; }
Whereas for a non auto-implemented property the backing field is upfront, visible as a private scoped variable.
Example:
private string log;
public string Log
{
get => log;
set => log = value;
}
Also, it is worth noted here is the 'getter' and 'setter' can use the different 'backing field'
A property is a like a layer that separates the private variable from other members of a class. From outside world it feels like a property is just a field, a property can be accessed using .Property
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName => $"{FirstName} {LastName}";
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return $"{FirstName} {LastName}"; } }
}
FullName is a Property. The one with arrow is a shortcut. From outside world, we can access FullName like this:
var person = new Person();
Console.WriteLine(person.FullName);
Callers do not care about how you implemented the FullName. But inside the class you can change FullName whatever you want.
Check out Microsoft Documentation for more detailed explanation:
https://learn.microsoft.com/en-us/dotnet/csharp/properties
Define the Private variables
Inside the Constructor and load the data
I have created Constant and load the data from constant to Selected List class.
public class GridModel
{
private IEnumerable<SelectList> selectList;
private IEnumerable<SelectList> Roles;
public GridModel()
{
selectList = from PageSizes e in Enum.GetValues(typeof(PageSizes))
select( new SelectList()
{
Id = (int)e,
Name = e.ToString()
});
Roles= from Userroles e in Enum.GetValues(typeof(Userroles))
select (new SelectList()
{
Id = (int)e,
Name = e.ToString()
});
}
public IEnumerable<SelectList> Pagesizelist { get { return this.selectList; } set { this.selectList = value; } }
public IEnumerable<SelectList> RoleList { get { return this.Roles; } set { this.Roles = value; } }
public IEnumerable<SelectList> StatusList { get; set; }
}
Properties are functions that are used to encapsulate data, and allow additional code to be executed every time a value is retrieved or modified.
C# unlike C++, VB.Net or Objective-C doesn’t have a single keyword for declaring properties, instead it uses two keywords (get/set) to give a much abbreviated syntax for declaring the functions.
But it is quite common to have properties, not because you want to run additional code when data is retrieved or modified, but because either you MIGHT want to do so in the future or there is a contract saying this value has to be a exposed as a property (C# does not allow exposing data as fields via interfaces). Which means that even the abbreviated syntax for the functions is more verbose than needed. Realizing this, the language designers decided to shorten the syntax even further for this typical use case, and added “auto” properties that don’t require anything more than the bare minimum, to wit, the enclosing braces, and either of the two keywords (separated by a semicolon when using both).
In VB.Net, the syntax for these “auto” properties is the same length as in c# —- Property X as String vs string X {get; set;}, 20 characters in both cases. It achieves such succinctness because it actually requires 3 keyword under the normal case, and in the case of auto properties can do without 2 of them.
Removing any more from either, and either a new keyword would have had to be added, or significance attached to symbols or white space.

C# Extension methods on "members"

I have some extension methods which could be used like this:
MyType myObject;
string displayName = myObject.GetDisplayName(x => x.Property);
The problem here is that it needs an instance, even if the extension method only needs the type MyType. So if there is no instance, it needs to be called like this:
string displayName = BlahBlahUtility.GetDisplayName((MyTpe x) => x.Property);
Which is not so nice anymore.
Is there a way to write better syntax for such cases?
What I actually want to do is this (pseudo language):
string displayName = MyType.Property.GetDisplayName()
Which of course does not work with C#.
But what about something like this:
string displayName = ((MyType x) => x.Property).GetDisplayName();
This is also not possible (after a lambda, a dot is not accepted).
Any ideas?
Edit:
My "favorite syntax" MyType.Property.GetDisplayName() seems to be misleading. I don't talk about static properties here. I know that this syntax won't be possible. I just tried to show in pseudo language, what information is necessary. This would be ideal, every additional stuff is just syntactical overhead. Any working syntax that is close to this would be great.
I don't want to write a certain extension method. I want an easy, readable and compile time safe syntax, using any language feature.
Have a look at the Express and Reflect classes in the Lokad Shared Libraries. Think they may help out with what you are trying to do. Read more here:
Strongly Typed Reflection in Lokad Shared
How to Find Out Variable or Parameter Name in C#?
From your comment: "I want an easy and compile time safe syntax to get information about members".
This is a very frequently requested feature and has been discussed in the C# team's meetings for about a decade, but has never been prioritised high enough to be included.
This blog post explains why:
http://blogs.msdn.com/ericlippert/archive/2009/05/21/in-foof-we-trust-a-dialogue.aspx
So for now, you're just going to be fighting against a missing feature. Maybe you could post more information about your broader problem and see if people can suggest different approaches.
Update
Without more info about your problem this is just guesswork. But if you have a property that represents a value but also carries additional "meta" information, you could always represent that as a new type and use an "injection" step to set everything up.
Here's a suggested abstract interface to such a "meta property":
public interface IMetaProperty<TValue>
{
TValue Value { get; set; }
string DisplayName { get; }
event Action<TValue, TValue> ValueChanged;
}
The value of the property is just another sub-property, with its type defined by the user.
I've put in the display name, and also as a bonus you've got an event that fires when the value changes (so you get "observability" for free).
To have properties like this in a class, you'd declare it like this:
public class SomeClass
{
public IMetaProperty<string> FirstName { get; private set; }
public IMetaProperty<string> LastName { get; private set; }
public IMetaProperty<int> Age { get; private set; }
public SomeClass() { MetaProperty.Inject(this); }
}
Note how the setters on the properties are private. This stops anyone from accidentally setting the property itself instead of setting the Value sub-property.
So this means the class has to set up those properties so they aren't just null. It does this by calling a magic Inject method, which can work on any class:
public static class MetaProperty
{
// Make it convenient for us to fill in the meta information
private interface IMetaPropertyInit
{
string DisplayName { get; set; }
}
// Implementation of a meta-property
private class MetaPropertyImpl<TValue> : IMetaProperty<TValue>,
IMetaPropertyInit
{
private TValue _value;
public TValue Value
{
get { return _value; }
set
{
var old = _value;
_value = value;
ValueChanged(old, _value);
}
}
public string DisplayName { get; set; }
public event Action<TValue, TValue> ValueChanged = delegate { };
}
public static void Inject(object target)
{
// for each meta property...
foreach (var property in target.GetType().GetProperties()
.Where(p => p.PropertyType.IsGenericType &&
p.PropertyType.GetGenericTypeDefinition()
== typeof(IMetaProperty<>)))
{
// construct an implementation with the correct type
var impl = (IMetaPropertyInit)
typeof (MetaPropertyImpl<>).MakeGenericType(
property.PropertyType.GetGenericArguments()
).GetConstructor(Type.EmptyTypes).Invoke(null);
// initialize any meta info (could examine attributes...)
impl.DisplayName = property.Name;
// set the value
property.SetValue(target, impl, null);
}
}
}
It just uses reflection to find all the IMetaProperty slots hiding in the object, and fills them in with an implementation.
So now a user of SomeClass could say:
var sc = new SomeClass
{
FirstName = { Value = "Homer" },
LastName = { Value = "Simpson" },
Age = { Value = 38 },
};
Console.WriteLine(sc.FirstName.DisplayName + " = " + sc.FirstName.Value);
sc.Age.ValueChanged += (from, to) =>
Console.WriteLine("Age changed from " + from + " to " + to);
sc.Age.Value = 39;
// sc.Age = null; compiler would stop this
If you're already using an IOC container you may be able to achieve some of this without going directly to reflection.
It looks like you're trying to create a static extension method?
DateTime yesterday = DateTime.Yesterday(); // Static extension.
Instead of
DateTime yesterday = DateTime.Now.Yesterday(); // Extension on DateTime instance.
If this is what you're trying to pull off, I do not believe it is possible in the current version of C#.
It sounds like you are integrating layers a little too tightly. Normally in this type of situation I would let the presentation layer decide the implementation of GetDisplayName() instead of making it an extension of the property itself. You could create an interface called MyTypeDisplayer or whatever you fancy, and let there be multiple implementations of it not limiting you to a single display implementation.
The issue here is that one cannot get a reference to non-static methods via instance MyType.[Member]. These can only be seen through a reference to an instance of the type. You also cannot build an extension method on-top of a type declaration, only on an instance of a type - that is the extension method itself has to be defined using an instance of a type (this T x).
One can however define the expression like this to get a reference to static members:
((MyType x) => MyType.Property)
One could do something similar to string displayName = ((MyType x) => x.Property).GetDisplayName();
The first issue is guaranteeing that the compiler treats your (x=> x.Property) as an Expression rather than an action/func etc...
To do this one might need to do this:
string displayName = ((Expression<Func<PropertyType>>)((MyType x) => x.Property).GetDisplayName();
The extension method would then have to be defined like this:
public static string GetDisplayName<T>(this Expression<Func<T>> expression)
You might also have to define an extension method on top of Expression<Action>> and Expression<Action<T>> if your members are also methods.
You can do a dot after an Expression - this is where the Compile method would reside.
Appended:
I think the static call to the extension method in cases that one doesn't have an instance of the type one needs to do "reflection" on to determine a Members name would be the cleanest syntax still - this way you could still use the extension method when using an instance of a type and fall back to the static call definition => MyExtensionClass.GetDisplayName(TypeOfX x => TypeOfX.StaticMember OR x.Property/Member) when one doesn't have an instance
If you interface your properties, you could make the extension on the interface instead:
namespace Linq1
{
class Program
{
static void Main(string[] args)
{
MyType o = new MyType();
o.Property.GetDisplayName();
}
}
public class MyType
{
public IDisplayableProperty Property { get; set; }
}
public interface IDisplayableProperty
{
string GetText();
}
public class MyProperty1 : IDisplayableProperty
{
public string GetText() { return "MyProperty2"; }
}
public class MyProperty2 : IDisplayableProperty
{
public string GetText() { return "MyProperty2"; }
}
public static class Extensions
{
public static string GetDisplayName(this IDisplayableProperty o)
{
return o.GetText();
}
}
}

Categories