Declare variable. Is this possible?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • shapper

    #1

    Declare variable. Is this possible?

    Hello,

    I am defining a class as follows:

    stat = new Stat {
    Count = Roles.GetUsersI nRole(RoleType. Administrator.T oString
    ()).Count(),
    Share = Count / UserCount * 100,
    UserCount = Membership.GetA llUsers().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.GetUsersI nRole(RoleType. Administrator.T oString()).Coun t
    () / Membership.GetA llUsers().Count * 100

    Thanks,
    Miguel
  • Jeroen Mostert

    #2
    Re: Declare variable. Is this possible?

    shapper wrote:
    I am defining a class as follows:
    >
    stat = new Stat {
    Count = Roles.GetUsersI nRole(RoleType. Administrator.T oString
    ()).Count(),
    Share = Count / UserCount * 100,
    UserCount = Membership.GetA llUsers().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.

    Comment

    Working...