tags:

views:

112

answers:

4

i have set mName, mContact and memail as my variables.. and i want to use them in setter and getters.. can any body help me doing so? only want to know the syntax..

regards..

A: 

Hi,

in VS 2005:

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}

in VS 2008:

public int CustomerId { get; set; }
//private declaration and property in one line coming with .net 3.5
MUG4N
+3  A: 

If you have an existing private variable and you want to expose some public properties then you should do the following:

private string mName;
public string Name
{
   get
   {
      return mName;
   }

   set
   {
      mName = value;
   }
}

You could also avoid the need for the internal private variable by using a Automatic Properties:

public string Name { get; set; }

As JWL has pointed out in the comments you can also set modifiers on getters and setters. Valid modifiers are private/internal/protected.

public string Name { get; private set; }
public string Name { protected get; set; }
rtpHarry
In addition to public string Name { get; set; } you can specify the scope for the setter or the getter with public string Name { get; private/internal/protected set; }
JWL_
+3  A: 

Visual Studio Tip:

Set your cursor inside of the field (Private int _i;) and Ctrl R + E This will create the property accessors for you :)

Mike
+1  A: 

It is also a good practice to implement checking, whether setting up the private variable is really necessary. Like this>


private string mName;
public string Name
{
   get
   {
      return mName;
   }

   set
   {
      if ( value != mName )
      {
           mName = value;
      }
   }
}

Daniel Pokrývka