Using value of propertie in his own custom attribute - c#

We use some DTOs in your business logic. I also use these DTOs for printing. So there is a custom attribute printable which will be used in the print-framework to recognize which properties to print. In some cases it is necessary to preformat the value for the printengine.
My idea was to use a construct like this:
[Printable(formatedValue = DoFormatingXY(MyProperty))]
public int MyProperty{ get; set; }
But unfortunatly this will not work (apart from the fact that it is unpleasant to have to use the propertie-name again):
Error An object reference is required for
the non-static field, method, or property '...MyPropertie.get'
So I understand what the problem is, but how can handle it? One idea was to use delegates, but there are a lot of formatting-methods with different method signatures.

Attributes are just metadata, not code. So change it to something like:
[Printable(FormatStyle = FormatStyles.XY)]
public int MyProperty{ get; set; }
Then the printer code can check for a FormatStyle parameter to the attribute and apply the requested format to the property.

Related

What's the reason for peoples to use properties with get; set; instead of fields?

I often see properties in classes, instead of fields. It looks like that:
class TestClass
{
public ulong Id { get; set; }
public string Description { get; set; }
}
Why peoples do this? They could use fields instead. I see at least single pro there - we can pass fields with ref keyword into functions. Is there any pro for properties or other reasons to use them like that?
The main reason is encapsulation - the value can only be changed trough the corresponding properties, and this continues to be the case even if you later decide that the property shouldn't just return a value. Maybe you find that you'll want to fire an event when a value changes? If you've got a property, that's very easy. If you've got a public field, you need to make a breaking change.
In addition, properties can be virtual or declared in interfaces. And they can be declared read-only.
Oh, and it helps in debugging: You can set a breakpoint on the "set", if you want to know who is changing your value (unexpectedly).
People use properties instead of fields mainly due to coding conventions. If it doesn't perform any actual encapsulation (in case of POCO), then there's not much of a difference in C#. Most of the times fields could be used instead of properties with no consequences whatsoever.
// This:
public string MyValue;
// Could be later on changed to this:
public string MyValue { get; set; }
// With no compatibility issues.
Although it's interesting to speculate why conventions are the way they are. In C# difference between properties and fields is mostly hidden from consumer standpoint. This is not necessarily the case in older languages. I.e. in Java you had to write getter and setter methods explicitly. So if you have a field in Java, and now you decide that you want to encapsulate it, then you would need to go over all usages of that field and use getters and setters instead. This could be even a bigger issue if you use dynamic library linking (that used to be popular style of deployment some time ago). Because of this it was easier to encapsulate fields from the start, so you wouldn't have backwards compatibility issues in the future. Naturally these conventions spread to other languages as well.

Why can't a field itself have getters/setters like properties do?

I'm a C# beginner, so easy explanations are greatly appreciated.
I was learning about properties, and got this question: properties give custom access logic to fields, but why can't the field itself contain its getter/setter? In other words, is there a reason why we can't get rid of Example and write custom get/setters under example(field)?
I could not find other posts that answer my question.
class MyClass
{
private int example = 5;
public int Example
{
get;
private set;
}
// here, this Example property only acts as a gateway for example.
// why is it not possible for the field 'example' to contain the
// get/set?
}
Property is an interface to Class, and not always is about storing data, you can always make the variable public member and will work perfectly like property, but the property has its own main job to work as an interface for that value with other classes.
While in many cases the property just works as public parameters, it is not always meant to be used in that way.

Newtonsoft custom ignore convention

I want to ignore certain properties in a class, but I want to keep the class POCO for many reasons. Hence I do not want to introduce dependency to Json.NET, and do not want to use JsonIgnoreAttribute.
Is there some way to customize the contract resolver to respect some other convention? Eg, properties that are named starting with the word "NonSerialized", for instance, or at least a custom attribute of our own choosing that is internally created (again to eliminate external dependency and keep the domain model as pure as possible).
Also different persistence will need to ignore/respect the same attribute differently, so it would be nice to be able to control what gets serialized at runtime via some kind of fluent api. Is this even possible?
For fields you can use [NonSerializable] attribute from System namespace, to avoid serialization. That way you have no dependency to external library. This doesn't work on properties.
For properties, there is a feature called Conditional Property Serialization. Basically, you implement method that returns boolean and follows naming convention - ShouldSerialize[PropertyName].
public class LoginModel
{
public string UserName { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
public bool ShouldSerializePassword() { return false; }
}
This example would always avoid serializing Password. ShouldSerialize method can contain more complex validation logic, instead of simply returning false.

using attributes vs conventional getting properties

I need to find all properties of a specific object which are not readonly and based on their type do something
I mean if the type of property is int i need to do sth and if it is string i should do something else
using reflection and get this type and conventionally i can create an object which can do what I want
for example if the property type is Int , I can create an instance of IntType:IType class
but I have another option: set an attribute for each property and based on these attributes,find suitable IType
I just cant decide which one is better?
If all the information you need is already contained in the type of the property, I can't see how introducing a new attribute is a good idea. Aside from anything else, you can easily forget to update the attribute when the data type changes. You start off with:
[Int32Type]
int Foo { get; set; }
then find you actually need it to be a long, but forget to change the attribute:
[Int32Type]
long Foo { get; set; }
Now you're probably going to be acting incorrectly on it.
If you're really adding information - e.g. if not all int properties need to be treated the same way - that's a different matter.

C# Automatic Properties

I'm a bit confused on the point of Automatic properties in C# e.g
public string Forename{ get; set; }
I get that you are saving code by not having to declare a private variable, but what's the point of a property when you are not using any get or set logic? Why not just use
public string Forename;
I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?
Properties can have code put into them without breaking contract, fields can't have code put into them without changing them to properties (and breaking the interface). Properties can be read only or write only, fields can't. Properties can be data bound, fields can't.
You can write
public string Forename{ get; private set; }
to get read-only properties... Still not nearly as versatile as real properties, but it's a compromise that for some works.
I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?
In the first case, the compiler will automatically add a field for you, and wrap the property. It's basically the equivalent to doing:
private string forename;
public string Forename
{
get
{
return this.forename;
}
set
{
this.forename = value;
}
}
There are many advantages to using properties over fields. Even if you don't need some of the specific reasons, such as databinding, this helps to future-proof your API.
The main problem is that, if you make a field, but in v2 of your application, need a property, you'll break the API. By using an automatic property up front, you have the potential to change your API at any time, with no worry about source or binary compatibility issues.
It is meant that you expect to add the logic later.
If you do so and have it as property from the beginning, you will not have to rebuild the dependent code. If you change it from a variable to a property, then you will have to.
Consider looking at some related threads about Difference Between Automatic Properties and Public Fields, Fields vs Properties, Automatic Properties - Useful or Not?, Why Not to Use Public Fields.
Public data members are evil (in that the object doesn't control modification of it's own state - It becomes a global variable). Breaks encapsulation - a tenet of OOP.
Automatic properties are there to provide encapsulation and avoid drudgery of writing boiler plate code for simple properties.
public string ID { get; set;}
You can change automatic properties to non-automatic properties in the future (e.g. you have some validation in a setter for example)... and not break existing clients.
string m_ID;
public string ID
{
get { return m_ID; }
set
{
//validate value conforms to a certain pattern via a regex match
m_ID = value;
}
}
You cannot do the same with public data attributes. Changing a data attribute to a property will force existing clients to recompile before they can interact again.
When adding auto properties the compiler will add get set logic into the application, this means that if you later add to this logic, and references to your property from external libraries will still work.
If you migrated from a public variable to a property, this would be a breaking change for other libraries that reference yours - hence, why not start with an auto property? :)
For one, you can set the property to virtual and implement logic in an inheriting class.
You can also implement logic in the same class afterwards and there won't be side-effects on any code relying on the class.
Not all properties need get/set logic. If they do, you use a private variable.
For example, in a MV-something pattern, your model would not have much logic. But you can mix and match as needed.
If you were to use a field like you suggested in place of a property, you can't for example define an interface to describe your class correctly, since interfaces cannot contain data fields.
A property is like a contract, and you can change the implemenation of a property without affecting the clients using your classes and properties. You may not have any logic today, but as business requirements change and if you want to introduce any code, properties are your safest bet. The following 2 links are excellent c# video tutorials. The first one explains the need of properties over just using fields and the second video explains different types of properties. I found them very useful.
Need for the Properties in C#
Poperties in C#, Read Only, Write Only, Read/Write, Auto Implemented
Take a look at the following code and explanation.
The most common implementation for a property is getter or a setter that simply reads and writes to a private field of the same type as a property. An automatic property declaration instructs the compiler to provide this implementation. The compiler automatically generates a private backing field.
Look into the following code:-
public class Stock
{
decimal currentPrice ; // private backing field.
public decimal CurrentPrice
{
get { return currentPrice ; }
set { currentPrice = value ; }
}
}
The same code can be rewritten as :-
public class Stock
{
public decimal CurrentPrice { get ; set ; } // The compiler will auto generate a backing field.
}
SOURCE:- C# in a Nutshell

Categories