1

Can I make a property in c# class that has no field, but I still can check the value and set it only if match?

I mean something like this:

public int Num
{
    get;
    set if value > 0 && value < 100;
}

I know that I can do this:

private int num;
public int Num
{
    get
    {
        return num;
    }
    set
    {
        if (value > 0 && value < 100)
            num = value;
    }
}

But I want to do it without using a field, and just using property. Is it possible?

Dvir
  • 19
  • 1
  • 2

2 Answers2

2

To be clear: btw; it's not that the property won't be set to that value, it's just a different way to look at your question.

You can use attributes, but you'll need a way to validate them. For instance; the Range attribute:

[Range(0,100, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
public int Num {get; set;}

So, this is typically used in MVC or EF like applications where the attributes are being checked by that particular framework.

There is some more info about that subject here: https://msdn.microsoft.com/en-us/library/cc668215(v=vs.110).aspx

It can also work in MVVM WPF applications, but again, you'll need a framework for that.

btw; it's not that the property won't be set to that value, it's just a different way to look at your question.

So if your use case is actually how to restrict and easily apply some business rules on a view or data-model, this is an accepted method. If you keep it to your original question can I do a conditional set without an if and a field?, the answer is no.

Some more attributes can be found here.

Stefan
  • 17,448
  • 11
  • 60
  • 79
  • She/He probably couldn't find the library and just down-voted... It happens frequently, there's nothing wrong about your answer. – Thadeu Fernandes Nov 24 '17 at 19:00
  • 1
    @ThadeuFernandes: thank you, I always hope people leave comments on a down-vote so the answer can be improved or better explained. – Stefan Nov 24 '17 at 19:02
1

I think the answer is no. You may want to see this one and this one to know why.

Fields are ordinary member variables or member instances of a class. Properties are an abstraction to get and set their values.

by doing the first block, you just break shorthand that already defined in C# and if you want to implement that idea, I think @Stefan proposed a good one.

looooongname
  • 107
  • 2
  • 14
  • Why, you can just store the value in an external/static dictionary WeakRef(this) -> value. – Vlad Nov 24 '17 at 19:17
  • @Vlad Why would you want to involve a static dictionary just to avoid having a field on the class? – JLRishe Nov 24 '17 at 19:47
  • @JLRishe: Well, because that's a question we are discussing here :) Besides, WPF does this for dependency properties: most of them have default values, so this allows to reduce memory consumption drastically. – Vlad Nov 24 '17 at 21:42