By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,471 Members | 722 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,471 IT Pros & Developers. It's quick & easy.

Declare variable. Is this possible?

P: n/a
Hello,

I am defining a class as follows:

stat = new Stat {
Count = Roles.GetUsersInRole(RoleType.Administrator.ToStri ng
()).Count(),
Share = Count / UserCount * 100,
UserCount = Membership.GetAllUsers().Count
};

Is there a way to make:
Share = Count / UserCount * 100,

To work?

I mean, at the moment, Count and UserCount are not being recognized.
I understand why ... I am just trying to figure if there is a way to
declare this instance in one step without repeating the code like:

Share = Roles.GetUsersInRole(RoleType.Administrator.ToStri ng()).Count
() / Membership.GetAllUsers().Count * 100

Thanks,
Miguel
Nov 19 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
shapper wrote:
I am defining a class as follows:

stat = new Stat {
Count = Roles.GetUsersInRole(RoleType.Administrator.ToStri ng
()).Count(),
Share = Count / UserCount * 100,
UserCount = Membership.GetAllUsers().Count
};

Is there a way to make:
Share = Count / UserCount * 100,

To work?
Sure. Write it *after* your object initializer:

stat = new Stat { ... };
stat.Share = stat.Count / stat.UserCount * 100;

Note that underneath, this is what the C# compiler is doing anyway: "x = new
X { A = a, B = b }" is implemented as "x = new X(); x.A = a; x.B = b;".
Object initializers are neat, but it's not a disaster if you can't write
everything down neatly.

Also, if "Share" is always completely defined by Count and UserCount,
consider making it a property without storage instead:

class Stat {
...
double Share {
get {
return UserCount == 0 ? 0 : Count * 100.0 / UserCount;
}
}
}

Assigning to Share is now neither necessary nor possible.

--
J.
Nov 19 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.