Declare variable. Is this possible?

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I am defining a class as follows:

stat = new Stat {
Count = Roles.GetUsersInRole(RoleType.Administrator.ToString
()).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.ToString()).Count
() / Membership.GetAllUsers().Count * 100

Thanks,
Miguel
 
shapper said:
I am defining a class as follows:

stat = new Stat {
Count = Roles.GetUsersInRole(RoleType.Administrator.ToString
()).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.
 
Back
Top