c#: getter/setter - c#

I saw something like the following somewhere, and was wondering what it meant. I know they are getters and setters, but want to know why the string Type is defined like this. Thanks for helping me.
public string Type { get; set; }

Those are Auto-Implemented Properties (Auto Properties for short).
The compiler will auto-generate the equivalent of the following simple implementation:
private string _type;
public string Type
{
get { return _type; }
set { _type = value; }
}

That is an auto-property and it is the shorthand notation for this:
private string type;
public string Type
{
get { return this.type; }
set { this.type = value; }
}

In C# 6:
It is now possible to declare the auto-properties just as a field:
public string FirstName { get; set; } = "Ropert";
Read-Only Auto-Properties
public string FirstName { get;} = "Ropert";

public string Type { get; set; }
is no different than doing
private string _Type;
public string Type
{
get { return _Type; }
set { _Type = value; }
}

This means that the compiler defines a backing field at runtime. This is the syntax for auto-implemented properties.
More Information: Auto-Implemented Properties

It's an automatically backed property, basically equivalent to:
private string type;
public string Type
{
get{ return type; }
set{ type = value; }
}

These are called auto properties.
http://msdn.microsoft.com/en-us/library/bb384054.aspx
Functionally (and in terms of the compiled IL), they are the same as properties with backing fields.

You can also use a lambda expression
public string Type
{
get => _type;
set => _type = value;
}

With the release of C# 6, you can now do something like this for private properties.
public constructor()
{
myProp = "some value";
}
public string myProp { get; }

Related

Is there a way to set a default function for getters and setters?

I was wondering if there is a way to set a default function for a getter or a setter.
For example, let's say I have this:
public class MyClass
{
public bool IsDirty {get; private set; } = false;
private string _property;
public string Property1
{
get
{
return _property1;
}
set
{
if (value != _property1)
{
_property1 = value;
IsDirty = true;
}
}
}
}
I was wondering if there was a way to do something like this:
public class MyClass
{
public bool IsDirty {get; private set;} = false;
MyClass.defaultSet = { if (value != !_property1) { _property1 = value; IsDirty = true; } };
private string _property1;
public string Property1 { get; set; }
public string Property2 {get; set;}
public string Property3 {get; set;}
//...
}
So that I don't have to do it the first way on this big class I have (~100 properties).
You can reduce the noise by using a helper method like this
private void Set<T>(ref T field, T value)
{
if (!Equals(value, field))
{
field = value;
IsDirty = true;
}
}
Then you can write:
public string Property1
{
get => _property1;
set => Set(ref _property1, value);
}
No, this doesn't exist, for several reasons:
Not every property is going to be a string, so this would need to correctly handle integers, DateTimes, Decimal, etc
Primitive value types are bad enough, but then start throwing in things like Tuples, complex classes (where changing a class member is still get operation on the property itself!), delegates, etc
If you reference a property by it's own name, you're creating a circular reference that will cause a StackOverflowException.
Not every property is going to use the same Property name, so that part of the method is different. You'd need another keyword or argument to the set method.
You need a way to exempt the someBool / IsDirty property.

What does {get; set;} means ? [duplicate]

This question already has answers here:
What is the { get; set; } syntax in C#?
(20 answers)
Closed 9 years ago.
Consider the following code :
public class Order
{
public int OrderID { get; set; }
public DateTime OrderDate { get; set; }
public decimal Total { get; set; }
}
I don't understand what does the { get; set; } means .
I usually use get and set like this :
class Person
{
private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
set
{
name = value;
}
}
}
So, what does the { get; set; } means ?
Thanx
Using { get; set; } by itself translates exactly to what you usually use.. its just shorthand for it.
The compiler creates an automatic backing field.
So this:
public string FirstName { get; set; }
..is compiled to this:
private string _firstName;
public string FirstName {
get {
return _firstName;
}
set {
_firstName = value;
}
}
This all happens at compile time, therefore you cannot directly access the backing field (because it isn't actually available until the code is compiled).
After the compiler converts the above.. automatic properties are actually turned into methods.
So the above is turned into this:
public void set_FirstName(string value) {
_firstName = value;
}
public string get_FirstName() {
return _firstName;
}
Then some IL is produced to notify tools like Visual Studio that they are properties and not methods.. somewhat like this:
.property instance string FirstName() {
.get instance string YourClass::get_FirstName()
.set instance void YourClass::set_FirstName(System.String)
}
These are auto implemented properties.
Compiler will extend it with a backing field for you. However, you can't access that field directly.
In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. 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.
Read more on MSDN: Auto-Implemented Properties (C# Programming Guide)

Setting only a setter property

I have an object model that has a property like this:
public class SomeModel
{
public string SomeString { get; set; }
public void DoSomeWork()
{
....
}
}
I want the DoSomeWork function to execute automatically after the SomeString property changes. I tried this but it's not working:
public string SomeString { get; set { DoSomeWork(); } }
What's the correct syntax?
Use a private field instead, like this ...
public class SomeModel
{
private string someString = "";
public string SomeString {
get { return this.someString; }
set {
this.someString = value;
this.DoSomeWork();
}
}
public void DoSomeWork()
{
....
}
}
You can't do this with automatic properties - you'll have to create a "manual" property backed by a field.
private string _someString;
public string SomeString
{
get { return _someString; }
set
{
_someString = value;
DoSomeWork();
}
}
If you really can't deal with this boilerplate (say you'd have to do this hundreds of times), consider using an AOP framework like PostSharp to implement this on your behalf - you'd just need to declare an automatic property and an attribute to get the binary rewriter to implement the desired scheme.
This will work...
private string _someString;
public string SomeString { get { return _someString; } set { _someString = value; DoSomeWork(); } }
private string _someString;
public string SomeString
{
get
{
return _someString;
}
set
{
DoSomeWork();
_someString = value;
}
}
C# team has introduced the auto-implement properties in C# 3.0. with the logic of minimizing the model making which is backed by an anonymous field created by compiler. this one is used when you don't need to implement any additional logic on a property of an object class. so it just followed as.
public string Name{ get; set;}// auto-implemented property. no additional logic.
if we want to add some logic as you want to add one function. we must be writing a manual property backed by a private field as like below.
private string _Name;
public string Name
{
get {return _Name;}
set {
_Name=value;
DoSomething(); //Additional logic implemented.
}
}

Automatic Properties (LINQ)

Would someone be able to explain or provide a link to a page that describes what Automatic Properties are (in relation to LINQ) in lamens terms please
Automatic properties - better call them "auto-implemented properties", are a new syntax sugar added in latest C# versions as some comment pointed out.
It consist in a property that declare its accessors without body and C# compiler creates the corresponding private fields for you:
public string Name
{
get;
set;
}
Note that this isn't an abstract member, becase it'd be marked with the appropiate attribute "abstract"!
Additionally to that, these accessors, as non-auto-implemented ones, can have visibility attributes: private, internal, public (default behavior):
public string Name
{
private get;
internal set;
}
Here is an automatic property in C# 3.0:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
compared to a non automatic property:
public class Person
{
string _FirstName;
string _LastName;
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
}
Here's the post by Dan Wahlin on automatic properties, from where I got the above code.
Refer to the following:
Auto-Implemented Properties
Using Automatic Properties in LINQ

Set a default value to a property

Is it possible to set a default value without the body of a property? Preferably with annotations.
[SetTheDefaultValueTo(true)]
public bool IsTrue { get; set; }
[SetTheDefaultValueTo(false)]
public bool IsFalse { get; set; }
public void Something()
{
var isTrue = this.IsTrue;
var isFalse = this.IsFalse;
}
No, there is no built-in way to set the value of a property with metadata. You could use a factory of some sort that would build instances of a class with reflection and then that could set the default values. But in short, you need to use the constructors (or field setters, which are lifted to the constructor) to set the default values.
If you have several overloads for your constructor, you may want to look at constructor chaining.
Using C# 6+, you are able to do something like this...
public string MyValue { get; set; } = "My Default";
Oh, it gets more fun because people have even requested something like this...
// this code won't compile!
public string MyValue {
private string _myValue;
get { return _myValue ?? "My Default"; }
set { _myValue = value; }
}
... the advantage being that you could control the scope of the field to only be accesible in the property code so you don't have to worry about anything else in your class playing with the state without using the getter/setter.
Assign the default property value in the class constructor.
class MyClass
{
public MyClass()
{
IsTrue = true;
IsFalse = false;
}
public bool IsTrue { get; set; }
public bool IsFalse { get; set; }
[...]
public void Something()
{
var isTrue = this.IsTrue;
var isFalse = this.IsFalse;
}
}
If you are using C#5 and earlier, you have to do it in a constructor.
but since C# 6.0, the ability to have auto property initializers is included, and the syntax is:
public int myage { get; set; } = 33;
Old thread.
Looks like Microsoft heard and this feature is available in .Net Framework 4.6+ (C# 6+)
You can use it like
public string MyValue { get; set; } = "My Default";
In this very specific example, you sort of can:
public bool IsFalse { get; set; }
public bool IsTrue
{
get { return !IsFalse; }
set { IsFalse = !value; }
}
public void Something()
{
var isTrue = this.IsTrue;
var isFalse = this.IsFalse;
}
But, in general, no.

Categories

Resources