Rakshith Murukannappa
Rakshith Murukannappa

Reputation: 589

Assign property value automatically from other properties within an object

I have the following Class

public class BlogPost
{
    public int BlogPostId             { get; set; }
    public string BlogPostTitle       { get; set; }
    public string BlogPostDescription { get; set; }
    public int Upvotes    { get; set; }
    public int Downvotes  { get; set; }
    public int TotalVotes { get; set; }
}

How would you automatically assign TotalVotes = Upvotes - Downvotes ?

Upvotes: 2

Views: 117

Answers (3)

Dharani Kumar
Dharani Kumar

Reputation: 457

The answers by others would work , but I would prefer something like this (C# 6.0)

public class BlogPost
{
    public int BlogPostId { get; set; }
    public string BlogPostTitle { get; set; }
    public string BlogPostDescription { get; set; }
    public int Upvotes { get; set; }
    public int Downvotes { get; set; }
    public int TotalVotes {get => GetTotalVotes(); }   

    // A method just in case if you need to do some extra calculations or validations
    private int GetTotalVotes()
    {

        //I am assuming the TotalVotes should not go below 0;
        //You can change it as you like

        int value = UpVotes - DownVotes;

        return value<0? 0 : value;

    }
}

Upvotes: 0

Salah Akbari
Salah Akbari

Reputation: 39966

Sounds like you are looking for a calculated property. So it should be something like this:

public int TotalVotes
{ 
    get { return Upvotes - Downvotes; } 
}

Or if you are using C# 6+ you can use expression body like this:

public int TotalVotes => Upvotes - Downvotes;

Upvotes: 2

Hubii
Hubii

Reputation: 348

You Need just to write your Operation in the return Path like:

public int TotalVotes { get { return Upvotes - Downvotes;} }

Upvotes: 0

Related Questions