Dvir
Dvir

Reputation: 19

C# property set if

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?

Upvotes: 1

Views: 3163

Answers (2)

Stefan
Stefan

Reputation: 17658

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.

Upvotes: 2

looooongname
looooongname

Reputation: 117

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.

Upvotes: 1

Related Questions